Python3基础之异常结构
程序员文章站
2022-04-14 22:57:28
自定义异常类 python class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) python try: raise MyE ......
自定义异常类
class ShortInputException(Exception): def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast
try: s = input('Please Input --> ') if len(s)<3: raise ShortInputException(len(s), 3) except EOFError: print('You input a end mark EOF') except ShortInputException as x: print('ShortInputException: length is {0:,}, at least is {1:,}'.format(x.length, x.atleast)) else: print('no error and everything is ok.')
Please Input --> yuxingliangEOF no error and everything is ok.
class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
try: raise MyError(2*2) except MyError as e: print('My exception occurred, value: ', e.value)
My exception occurred, value: 4
0. 断言语句的应用
assert
作用:确认条件表达式是否满足,一般和异常处理结构一起使用。
结构:
assert 条件表达式, '表达式error时,给出此处的判定字符串提示。'
a,b = 3, 5 assert a == b, 'a must be equal to b.' #判定a是否等于b,if a != b,抛出异常
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-7-2ad85e920458> in <module>() 1 a,b = 3, 5 ----> 2 assert a == b, 'a must be equal to b.' #判定a是否等于b,if a != b,抛出异常 AssertionError: a must be equal to b.
try: assert a == b, 'a must be equal to b' except AssertionError as reason: print('%s:%s'%(reason.__class__.__name__, reason))
AssertionError:a must be equal to b
1. try...except... 结构
- 如果try子句中的代码引发异常并被except子句捕捉,则执行except子句的代码块;
-
如果try子句中的代码块没有出现异常,则except子句代码块不执行,继续往后执行。
try: #可能会引发异常的代码,先执行以下试试看 except: #如果try中的代码抛出异常并被except捕捉,则执行此处的代码语句
"""代码功能:决策用户输入的是否是一个数字。 代码功能详细描述:while语句主导的死循环。 首先要求用户输入,然后就用户的输入进行判定: 尝试try中的语句 用户输入正确的数字,将输入的数字字符转换成数字,然后打印出提示信息,break掉循环 用户输入错误的字符,try中的语句检测到错误,然后被exception捕捉到,马上转到except中的语句执行,打印错误信息 虽有开始下一步的循环,知道用户输入正确的数字字符,采用break语句终止循环。""" while True: x = input('Please input: ') try: x = int(x) print('You have input {0}'.format(x)) break except Exception as e: print('Error.')
Please input: a Error. Please input: 234f Error. Please input: 6 You have input 6
2. try...except...else...结构
try | except | else |
---|---|---|
检测语句 | 有问题,执行相应的处理代码 | 不执行else语句 |
检测语句 | 没问题,不执行except语句 | 执行else下的语句 |
try: #可能会引发错误的代码 except Exception as reason: #用来处理异常的代码 else: #如果try中的子句代码没有引发异常,就执行此处的代码
while True: x = input('Please input: ') try: x = int(x) # 此处是可能引发异常的语句 except Exception as e: print('Error.') # 处理异常的语句 else: # 没有异常时,处理的语句 print('You have input {0}'.format(x)) break
Please input: a Error. Please input: b Error. Please input: 664h Error. Please input: 666 You have input 666
3. try...except...finally...结构
try | except | finally |
---|---|---|
尝试语句 | 有问题,执行相应的处理代码 | 始终执行finally语句 |
尝试语句 | 没问题,不执行except语句 | 始终执行finally语句 |
try: #可能会引发错误的代码 except Exception as reason: #用来处理异常的代码 finally: #不论try中是否引发异常,始终执行此处的代码
def div(a,b): try: print(a/b) except ZeroDivisionError: print('The second parameter cannot be 0.') finally: print(-1)
div(3,5)
0.6 -1
div(3,0)
The second parameter cannot be 0. -1
如果try子句中的异常没有被except语句捕捉和处理,或者except子句或者else子句中的代码抛出的了异常,
那么这些异常将会在finally子句执行完毕之后再次抛出异常。
div('3',5)
-1 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-15-dc6751a7464e> in <module>() ----> 1 div('3',5) <ipython-input-12-d5530669db53> in div(a, b) 1 def div(a,b): 2 try: ----> 3 print(a/b) 4 except ZeroDivisionError: 5 print('The second parameter cannot be 0.') TypeError: unsupported operand type(s) for /: 'str' and 'int'
4. 捕捉多种异常的结构
try: #可能会引发异常的代码 except Exception1: #处理异常类型1的代码 except Exception2: #处理异常类型2的代码 except Exception3: #处理异常类型3的代码 . . .
try: x = float(input('Please the first number: ')) y = float(input('Please the second number: ')) z = x/y except ZeroDivisionError: print('the second number isnot 0.') except TypeError: print('the number must be number.') except NameError: print('The variable isnot here.') else: print(x, '/', y, '=', z)
Please the first number: 30 Please the second number: 5 30.0 / 5.0 = 6.0
try: x = float(input('Please the first number: ')) y = float(input('Please the second number: ')) z = x/y except (ZeroDivisionError, TypeError, NameError): print('Error is catched.') else: print(x, '/', y, '=', z)
Please the first number: 45 Please the second number: 0 Error is catched.
5. 多种结构混合
def div(x,y): try: print(x/y) except ZeroDivisionError: print('ZeroDivisionError') except TypeError: print('typeerror') else: print('no error') finally: print('I am executing finally clause.')
div(3,4)
0.75 no error I am executing finally clause.
上一篇: 匿名函数
下一篇: 折耳根是鱼腥草吗,折耳根的功效与作用?