I. Throwing an exception
Python uses an Exception object (Exception object) to represent an exception, and an exception is thrown when an error is encountered. If the exception object is not handled or captured, the program terminates execution with the so-called backtracking (Traceback, an error message).
Raise statements
The Raise keyword in Python is used to throw an exception, basically the same as the throw keyword in C # and Java, as follows:
Import Tracebackdef throw_error (): raise Exception ("throws an exception") #异常被抛出, the print function cannot execute print ("Flying Pig") Throw_ Error ()
#运行结果:
"' Traceback (most recent): File" C:\Users\Administrator\Desktop\systray.py ", line 7, in
throw_ Error () File "C:\Users\Administrator\Desktop\systray.py", line 4, in Throw_error raise Exception ("Throw an exception") #异常被抛出, The print function cannot execute exception: throws an exception '
The Raise keyword is followed by a generic exception type (Exception), which generally throws an exception the more detailed the better
Two. Passing Exceptions:
Catching an exception, but trying to re-throw it (passing an 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: Raiseapp = Mufcalc () app.calc (2/0)
three. Custom Exception Types :
Python can also customize its own special type of exception, only to inherit from the exception class (directly or indirectly):
Class Myerror (Exception): Pass