This article provides a brief summary of simple applications that throw exceptions and customize exceptions in Python and pass exceptions. For more information, see
1. throw an exception
Python uses an exception object to indicate exceptions. An exception is thrown when an error occurs. If the exception object is not processed or captured, the program terminates the execution with the so-called trace (Traceback, an error message.
Raise statement
The raise keyword in Python is basically the same as the throw keyword in C # and Java, as shown below:
Import tracebackdef throw_error (): raise Exception ("throwing an Exception") # The Exception is thrown, and the print function cannot execute print ("Fliggy") throw_error ()
# Running result:
'''Traceback (most recent call last): File "C: \ Users \ Administrator \ Desktop \ Parse Ray. py", line 7, in
Throw_error () File "C: \ Users \ Administrator \ Desktop \ audit Ray. py ", line 4, in throw_error raise Exception (" throwing an Exception ") # The Exception is thrown, and the print function cannot execute Exception: throwing an Exception '''
The raise keyword is followed by a general Exception type (Exception). Generally, the more detailed the Exception is, the better.
II. transfer exception:
If an exception is caught, but you want to re-raise 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)
III. Custom exception types:
You can also customize your own special types of exceptions in Python. you only need to inherit from the Exception class (either directly or indirectly:
class MyError(Exception): pass