Home > Article > Backend Development > A brief discussion on Python throwing exceptions, custom exceptions, and passing exceptions
1. Throw exception
Python uses exception objects to represent abnormal situations. When an error is encountered, an exception will be thrown. If the exception object is not handled or caught, the program will terminate execution with a so-called traceback (an error message).
raise statement
The raise keyword in Python is used to raise an exception, which is basically the same as the throw keyword in C# and Java, as shown below:
import traceback def throw_error(): raise Exception("抛出一个异常")#异常被抛出,print函数无法执行 print("飞天猪") throw_error()
#Run result:
'''Traceback (most recent call last): File "C:\Users\Administrator\Desktop\systray.py", line 7, in <module> throw_error() File "C:\Users\Administrator\Desktop\systray.py", line 4, in throw_error raise Exception("抛出一个异常")#异常被抛出,print函数无法执行 Exception: 抛出一个异常'''
After the raise keyword, the throw is a general exception type (Exception). Generally speaking, the more detailed the exception thrown, the better
2. Transmission exception:
If you catch an exception, but want to re-raise it (pass the exception), you can use the raise statement without parameters:
class MufCalc(object): m = False def calc(self,exp): try: return eval(exp) except ZeroDivisionError: if self.m: print("cool") else: raise app = MufCalc() app.calc(2/0)
3. Custom exception type :
You can also customize your own special types of exceptions in Python, just inherit from the Exception class (directly or indirectly):
class MyError(Exception): pass