Exceptions are raised automatically when a program throws an error. In addition, Python also allows programs to raise exceptions on their own, which is done with the raise statement.
Very often, the decision of whether the system should raise an exception may need to be based on 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 due to inconsistency with business requirements must be raised at the discretion of the programmer; the system cannot raise such exceptions.
If you need to raise your own exception in your program, you should use the raise statement. raise statement has three common uses:
- raise: a single raise that raises an exception caught in the current context (such as in an except block) or raises a RuntimeError exception by default.
- raise Exception Class: raises followed by an exception class. This statement raises a default instance of the specified exception class.
- raise Exception object: raises the specified exception object.
All three of the above uses end up raising an instance of the exception (even if the exception class is specified, it actually raises the default instance of that class), and the raise statement can only raise one instance of the exception at a time.
The raise statement can be used to rewrite the code that handled the user input in the previous backgammon game:
try : # Separate the user-entered string into two strings with a comma ( , ) as separator x_str, y_str = (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 have entered are not legal, please re-enter them. The coordinates of the game should be in the format x,y.") continue
The code in line 7 of the program above uses the raise statement to raise its own exception, which it considers to be an exception when the user tries to move to a coordinate point that already has a piece. When the Python interpreter receives a developer-raised exception, it also aborts the current execution flow and jumps to the exception's except block, which handles the exception. In other words, there's no difference in how the Python interpreter handles exceptions, whether they're thrown by the system or by the programmer.
Even if the exception was thrown by the user, you can catch it with a try except. Of course, you can also leave it alone and let the exception propagate upwards (caller first), and if it reaches the Python interpreter, the program will abort.
The following example demonstrates two ways of handling exceptions raised by the user:
def main(): try: # Use try... .except to catch exceptions # At this point, even if the program throws an exception, it won't be propagated to the main function mtd(3) except Exception as e: print('An exception occurred in the program:', e) # Without using try... .except to catch exceptions, which can propagate and cause the program to abort. mtd(3) def mtd(a): if a > 0: raise ValueError("The value of a is greater than 0 and does not fulfill the requirement.") 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 it can call mtd(3) directly, so that the exception of the function will be propagated directly to the calling function, which will lead to the abort of the program if the function does not deal with the exception as well.
Run the above program to see the following output:
Program Exception: value of a is greater than 0, does not meet requirements
Traceback (most recent call last):
File "C:\Users\mengma\Desktop\", line 13, in <module>
main()
File "C:\Users\mengma\Desktop\", line 9, in main
mtd(3)
File "C:\Users\mengma\Desktop\", line 12, in mtd
raise ValueError("The value of a is greater than 0 and does not meet the requirements.")
ValueError: value of a is greater than 0, does not meet the requirement
The first line of output above is the result of the first call to mtd (3), which raises an exception that is caught and handled by the except block. The next chunk of output is the result of the second call to mtd (3), and since the exception was not caught by the except block, it propagates upwards until it is passed to the Python interpreter, causing the program to abort.
The second call to mtd(3) triggers three lines of output starting with "File", which actually shows the propagation path of the exception. That is, if the program doesn't handle the exception, Python will output the propagation of the exception on the console by default.
Customized Exception Classes
In many cases, programs may choose to raise custom exceptions because the class name of the exception usually contains useful information about the exception as well. Therefore, when raising an exception, it is important to choose an appropriate exception class so that the exception can be clearly described. In such cases, applications often need to raise custom exceptions.
User-defined exceptions should be inherited from the Exception base class or a subclass of Exception. There is basically no need to write more code when customizing the exception class, as long as you specify the parent class of the custom exception class.
The following program creates a custom exception class (Program 1):
class AuctionException(Exception): pass
The above program creates the AuctionException exception class, which does not require a class body definition, so it is sufficient to use the pass statement as a placeholder.
In most cases, creating a custom exception class can be accomplished with code similar to Program 1, simply by changing the class name of the AuctionException exception so that the exception's class name accurately describes the exception.
Except and raise are used together
In practice, exceptions may require more complex handling. When an exception occurs, the exception cannot be fully handled by one method alone; several methods must collaborate to fully handle the exception. That is, in the current method where the exception occurs, the program only partially handles the exception, and some processing needs to be done in the caller of the method, so the exception should be raised again so that the caller of the method can also catch the exception.
In order to accomplish this by having multiple methods work together to handle the same exception, you can combine a raise statement in an except block. The following program demonstrates how except and raise can be used together:
class AuctionException(Exception): pass class AuctionTest: def __init__(self, init_price): self.init_price = init_price def bid(self, bid_price): d = 0.0 try: d = float(bid_price) except Exception as e: # This simply prints the exception message print("Conversion out of anomaly:", e) # Throwing custom exceptions again raise AuctionException("Bids must be numerical and cannot contain other characters!") # ① raise AuctionException(e) if self.init_price > d: raise AuctionException("Bids lower than the starting price are not allowed!") initPrice = d def main(): at = AuctionTest(20.4) try: ("df") except AuctionException as ae: # Catch the exception in the bid() method again and handle the exception print('Exception caught by main function:', ae) main()
After the exception is caught by the except block in lines 9 to 13 of the above program, the system prints the exception string and then raises an AuctionException to notify the caller of the method to handle the AuctionException again. So the main() function in the program, the caller of the bid() method, can catch the AuctionException again, and then print out a detailed description of the exception.
This combination of except and raise is very common in real-world applications. The handling of exceptions in real-world applications is usually split into two parts:
The application backend requires logging to record details of exception occurrences;
The app also needs to communicate some sort of alert to the app user based on the exception;
In this case, all exceptions need to be done by both methods, so except and raise must be used together.
If the program needs to propagate the details of the original exception directly, Python also allows you to wrap the original exception in a custom exception by changing the code in ① above to the following form:
raise AuctionException(e)
raise takes no arguments
As you saw earlier, the raise statement can be used without arguments, and if the raise statement is in an except block, it will automatically raise the exception that is active in the current context; otherwise, it usually raises a RuntimeError exception by default.
For example, change the above program to the following form:
class AuctionException(Exception): pass class AuctionTest: def __init__(self, init_price): self.init_price = init_price def bid(self, bid_price): d = 0.0 try: d = float(bid_price) except Exception as e: # This simply prints the exception message print("Conversion out of anomaly:", e) # Throwing custom exceptions again raise if self.init_price > d: raise AuctionException("Bids lower than the starting price are not allowed!") initPrice = d def main(): at = AuctionTest(20.4) try: ("df") except AuctionException as ae: # Catch the exception in the bid() method again and handle the exception print('Exception caught by main function:', ae) main()
As you can see from line 13, the program is simply using a raise statement in the except block to raise the exception, and the raise statement will raise the exception caught by the except block again. Run the program and see the following output:
convert an anomaly (computing): could not convert string to float: 'df'
Exceptions caught by the main function: <class 'ValueError'>
Knowledge Points Supplement:
Demonstrate the use of raise
try: s = None if s is None: print "s is empty." raise NameError # If a NameError exception is thrown, the code that follows will not be executed. print len(s) # This sentence will not be executed, but the subsequent except will still go to the except TypeError: print "Empty object has no length" s = None if s is None: raise NameError print 'is here?' #If you don't use thetry......exceptthis form,Then just throw the exception,It won't go here.
trigger an exception
We can trigger the exception ourselves using the raise statement
The raise syntax is formatted as follows:
raise [Exception [, args [, traceback]]]
Exception is the type of exception (e.g., NameError) parameterized by any of the standard exceptions, and args is a self-supplied exception parameter.
The last argument is optional (and rarely used in practice) and, if present, is the trace exception object. To this point, this article on Python novice learn raise usage of the article is introduced to this, more related to Python in the use of raise content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!