1-13异常

In [1]:
import math
for i in range(10):
    try:
        input_number=input('write a number')
        if input_number=='q':
            break
        result=math.log(float(input_number))
        print (result)
#异常捕捉
    except ValueError:
        print('ValueError:imput must>0')
        #break
 
write a numberq
In [3]:
import math
for i in range(10):
    try:
        input_number=input('write a number')
        if input_number=='q':
            break
        result=1 /math.log(float(input_number))
        print (result)
#异常捕捉
    except ZeroDivisionError:
        print('log (value) must!=0')
        #break
 
write a numberq
In [4]:
import math
for i in range(10):
    try:
        input_number=input('write a number')
        if input_number=='q':
            break
        result=1 /math.log(float(input_number))
        print (result)
#异常捕捉
    except ValueError:
        print('ValueError:imput must>0')
    except ZeroDivisionError:
        print('log (value) must!=0')
    except Exception:
        print('Unknow error')
 
write a number-1
ValueError:imput must>0
write a number1
log (value) must!=0
write a number2
1.4426950408889634
write a numberq
In [5]:
class TangError(ValueError):
    pass
cur_list=['tang','yu','di']
while True:
    cur_input=input()
    if cur_input not in cur_list:
        raise TangError('Invaild input :%s' % cur_input)
 
q
 
---------------------------------------------------------------------------
TangError                                 Traceback (most recent call last)
 in ()
      5     cur_input=input()
      6     if cur_input not in cur_list:
----> 7raise TangError('Invaild input :%s' % cur_input)

TangError: Invaild input :q
In [6]:
try:
    print('hello')
finally:
    print('finally')#无论是否有异常都会执行
 
hello
finally
In [7]:
try:
    1/0
except:
        print('==0')
finally:
    print('finally')#无论是否有异常都会执行
 
==0
finally

你可能感兴趣的:(1-13异常)