python 异常处理 try except else finally raise
目的:为防止代码在运行中,因出现异常而崩溃,故添加异常处理机制,保持程序正常运行
格式
try:
执行的代码
except:
发生异常时执行的代码
else:
没有异常时执行的代码
finally:
不管有没有异常都会执行的代码
注:
-
try 只能有一个,except 可以有多个,else 和 finally 可以没有
-
except 的形式:
except:
except ValueError:
except ValueError as e:
except Exception as e: -
获取特定异常的相关信息:
try: 1/0 except Exception as e: print(e.args) # ('division by zero',) print(str(e)) # division by zero print(repr(e)) # ZeroDivisionError('division by zero')
-
手动抛出异常 raise:
a = int(input('input a:')) b = int(input('input b:')) if b==0 : raise ZeroDivisionError # ZeroDivisionError # raise # RuntimeError: No active exception to reraise # raise ZeroDivisionError('除数不能为零') # ZeroDivisionError: 除数不能为零 else: print(a/b)