When an error occurs in the program, the system automatically raises an exception. In addition, Python also allows programs to raise exceptions by themselves. Raising exceptions by themselves can be done with the raise statement.
In many cases, whether the system should cause an exception or not may need to be determined according to the business requirements of the application. If the data and execution in the program do not match the established business requirements, this is an exception. Exceptions generated due to inconsistencies with business requirements must be triggered by the programmer, and the system cannot cause such exceptions.
If you need to raise an exception yourself in the program, you should use the raise statement. The raise statement has the following three common uses:
The above three usages are ultimately to raise an exception instance (even if the exception class is specified, it is actually the default instance of that class). The raise statement can only raise one exception instance at a time.
You can use the raise statement to rewrite the code that processed user input in the previous Gobang game:
try:
# Use a comma (,) as a separator to separate the string entered by the user into two strings
x_str, y_str = inputStr.split(sep =",")
# If the point to be played is not empty
if board[int(y_str)-1][int(x_str)-1]!="+":
# Raise the default RuntimeError exception
raise
# Assign the corresponding list element to "●"
board [int(y_str)-1][int(x_str)-1]= ”●”
except Exception as e:print(type(e))
inputStr =input("The coordinates you entered are illegal, please re-enter, the coordinates for chess should be x,y format\n")continue
The 7th line of the code in the above program uses the raise statement to raise an exception by itself, and the program thinks that it is an exception when the user tries to play a chess with the coordinate point of an existing chess piece. When the Python interpreter receives an exception raised by the developer, it will also stop the current execution flow, jump to the except block corresponding to the exception, and the exception block will handle the exception. In other words, whether it is an exception that is automatically raised by the system or an exception that is triggered by the programmer, there is no difference in how the Python interpreter handles exceptions.
Even if the exception is raised by the user, you can use try except to catch it. Of course, you can ignore it and let the exception propagate upward (the caller first). If the exception is passed to the Python interpreter, the program will be aborted.
The following example demonstrates two ways to handle user exceptions:
def main():try:
# Use try...except to catch exceptions
# Even if the program is abnormal, it will not be propagated to the main function
mtd(3)
except Exception as e:print('The program is abnormal:', e)
# Do not use try...except catch exception, the exception will spread out and cause the program to abort
mtd(3)
def mtd(a):if a 0:
raise ValueError("The value of a is greater than 0, which does not meet the requirements")main()
As you can see from the above program, the program can either use try except to catch the exception when calling mtd(3), so that the exception will be caught by the except block and will not be propagated to the function that calls it; or directly call mtd(3) ), so that the exception of the function will be directly propagated to its calling function, if the function does not handle the exception, it will cause the program to abort.
Run the above program, you can see the following output:
The program is abnormal: the value of a is greater than 0, which does not meet the requirements
Traceback (most recent call last):
File “C:\Users\mengma\Desktop\1.py”, line 13, in <module
main()
File “C:\Users\mengma\Desktop\1.py”, line 9, in main
mtd(3)
File “C:\Users\mengma\Desktop\1.py”, line 12, in mtd
raise ValueError("The value of a is greater than 0 and does not meet the requirements")
ValueError: the value of a is greater than 0, which does not meet the requirements
The first line of output above is the result of the first call to mtd (3). The exception raised by this method is caught and processed by the except block. The subsequent large output is the result of the second call to mtd(3). Since the exception was not caught by the except block, the exception has been propagated upwards until it is passed to the Python interpreter and the program is aborted.
The three lines of output starting with "File" caused by the second call of mtd(3) actually display the abnormal propagation track information. In other words, if the program does not handle the exception, Python will output the propagation trajectory information of the exception on the console by default.
Custom exception class
In many cases, the program can choose to raise a custom exception, because the class name of the exception usually also contains useful information about the exception. Therefore, when an exception is raised, the appropriate exception class should be selected so that the exception situation can be clearly described. In this case, the application often needs to raise a custom exception.
User-defined exceptions should inherit the Exception base class or the subclasses of Exception. Basically, there is no need to write more code when customizing the exception class, just specify the parent class of the custom exception class.
The following program creates a custom exception class (program one):
classAuctionException(Exception): pass
The above program creates an AuctionException exception class, which does not require a class body definition, so the pass statement can be used as a placeholder.
In most cases, the creation of a custom exception class can be done by using code similar to that of Program 1. You only need to change the class name of AuctionException so that the class name of the exception can accurately describe the exception.
except and raise are used together
In actual applications, more complex handling methods may be required for exceptions. When an exception occurs, a method alone cannot completely handle the exception, and several methods must cooperate to completely handle the exception. In other words, in the current method where the exception occurs, the program only partially handles the exception, and some processing needs to be completed in the caller of the method, so the exception should be raised again so that the caller of the method can also catch abnormal.
In order to achieve this situation where multiple methods are used to co-process the same exception, it can be done by combining the raise statement in the except block. The following program demonstrates the simultaneous use of except and raise:
classAuctionException(Exception): pass
classAuctionTest:
def __init__(self, init_price):
self.init_price = init_price
def bid(self, bid_price):
d =0.0try:
d =float(bid_price)
except Exception as e:
# Here just simply print the exception information
print("Convert out exception:", e)
# Throw a custom exception again
raise AuctionException("The bid price must be numeric and cannot contain other characters!") # ①
raise AuctionException(e)if self.init_price d:
raise AuctionException("The bid price is lower than the starting price, so bidding is not allowed!")
initPrice = d
def main():
at =AuctionTest(20.4)try:
at.bid("df")
except AuctionException as ae:
# Catch bid again()The exception in the method, and handle the exception
print('The exception caught by the main function:', ae)main()
After the exception block corresponding to the 9~13 lines of code in the above program catches the exception, the system prints the string information of the exception, and then raises an AuctionException to notify the caller of the method to process the AuctionException again. Therefore, the main() function in the program, that is, the caller of the bid() method, can also catch the AuctionException again, and print out the detailed description of the exception.
This combination of except and raise is very common in practical applications. The actual application of exception handling is usually divided into two parts:
The application background needs to record the details of the abnormality through the log;
The application also needs to convey some kind of prompt to the application user based on the exception;
In this case, all exceptions need to be completed by two methods together, and must be combined with except and raise.
If the program needs to directly spread the detailed information of the original exception, Python also allows the original exception to be wrapped with a custom exception, as long as the code number ① above is changed to the following form:
raise AuctionException(e)
raise requires no parameters
As you have seen before, you can use the raise statement without parameters. At this time, the raise statement is in the except block, and it will automatically raise the exception activated by the current context; otherwise, it usually raises the RuntimeError exception by default.
For example, change the above program to the following form:
classAuctionException(Exception): pass
classAuctionTest:
def __init__(self, init_price):
self.init_price = init_price
def bid(self, bid_price):
d =0.0try:
d =float(bid_price)
except Exception as e:
# Here just simply print the exception information
print("Convert out exception:", e)
# Throw a custom exception again
raise
if self.init_price d:
raise AuctionException("The bid price is lower than the starting price, so bidding is not allowed!")
initPrice = d
def main():
at =AuctionTest(20.4)try:
at.bid("df")
except AuctionException as ae:
# Catch bid again()The exception in the method, and handle the exception
print('The exception caught by the main function:', ae)main()
As you can see from the 13 lines of code, the program simply uses the raise statement in the except block to raise an exception, then the raise statement will raise the exception caught by the except block again. Run the program, you can see the following output:
Converted an exception: could not convert string to float:'df'
The exception caught by the main function: <class ‘ValueError’
Knowledge point supplement:
Demo raise usage
try:
s = None
if s is None:
print "s is an empty object"
raise NameError #If a NameError exception is raised, the following code will not be executed
print len(s) #This sentence will not be executed, but the later except will still come
except TypeError:
print "Empty objects have no length"
s = None
if s is None:
raise NameError
print 'is here?' #If you don't use try......except this form, then throw an exception directly, it will not be executed here
Trigger exception
We can use the raise statement to trigger the exception ourselves
The syntax format of raise is as follows:
raise [Exception [, args [, traceback]]]
Exception in the statement is the type of the exception (for example, NameError). args is the exception parameter provided by itself.
The last parameter is optional (rarely used in practice), if it exists, it is to track the exception object. This is the end of this article about how to learn raise usage for Python novices. For more related content of raise usage in Python, please search for previous articles on ZaLou.Cn or continue to browse related articles below. Hope you will support ZaLou.Cn more in the future!
Recommended Posts