python exception handling try except else finally raise
Purpose: To prevent the code from crashing due to exceptions during operation, an exception handling mechanism is added to keep the program running normally
format
try:
执行的代码
except:
发生异常时执行的代码
else:
没有异常时执行的代码
finally:
不管有没有异常都会执行的代码
Note:
-
There can only be one try, multiple except, and none and finally
-
except 的形式:
except:
except ValueError:
except ValueError as e:
except Exception as e: -
Get information about a specific exception:
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')
-
Manually throw an exception 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)