Talking about python throws exceptions, custom exceptions, passing exceptions, and python throws
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 \ mongoray. py ", line 7, in <module> throw_error () File" C: \ Users \ Administrator \ Desktop \ empty 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