Preface
Is it possible to manually throw an exception at the specified location of the program? The answer is yes. Python allows us to manually set exceptions in the program and use the raise statement.
You may be puzzled, that is, we always try our best to make the program run normally, why do we need to manually set exceptions? First of all, we must distinguish between exceptions in the program and program execution errors. They are completely different things. The program's running exceptions caused by errors require programmers to find ways to solve them; but there are some exceptions, which are the result of normal operation of the program, such as exceptions manually caused by using raise.
The basic syntax format of a raise statement is:
raise [exceptionName [(reason)]]
Among them, the optional parameters enclosed with [] are optional, and their function is to specify the thrown exception name and the relevant description of the exception information. If all optional parameters are omitted, raise will throw the current error as is; if only reason is omitted, no exception description information will be attached when an exception is thrown.
In other words, there are three commonly used uses of the raise statement:
- Raise: a single raise. This statement raises an exception caught in the current context (such as in an except block), or raises a RuntimeError exception by default.
- raise Exception class name: raise followed by an exception class name, indicating that an exception of the execution type is raised.
- raise Exception class name (description information): At the same time as an exception of the specified type is raised, the exception description information is accompanied by exception description information.
Obviously, each time a raise statement is executed, it can only throw an exception that is executed once. First, let’s test the above 3 types of raise usages:
>>> raise Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> raise RuntimeError: No active exception to reraise >>> raise ZeroDivisionError Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> raise ZeroDivisionError ZeroDivisionError >>> raise ZeroDivisionError("The divisor cannot be zero") Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> raise ZeroDivisionError("The divisor cannot be zero") ZeroDivisionError: The divisor cannot be zero
Of course, we manually make the program throw exceptions, often not to make it crash. In fact, exceptions raised by raise statements are usually caught and processed using the try except (else finally) exception handling structure. For example:
try: a = input("Enter a number:") #Determine whether the user input is a number if(not ()): raise ValueError("a must be a number") except ValueError as e: print("Rendered exception:",repr(e))
The program run result is:
Enter a number: a
Throw an exception: ValueError('a must be a number',)
It can be seen that when the user inputs a number, the program will enter the if judgment statement and execute raise to raise a ValueError exception. But because it is in the try block, the exception thrown by raise will be caught by the try and processed by the except block.
Therefore, although the program uses the raise statement to raise an exception, the execution of the program is normal, and the manual thrown exception will not cause the program to crash.
raise No parameters required
As you can see earlier, you can use raise statements without parameters, for example:
try: a = input("Enter a number:") if(not ()): raise ValueError("a must be a number") except ValueError as e: print("Rendered exception:",repr(e)) raise
The program execution result is:
Enter a number: a
Throw an exception: ValueError('a must be a number',)
Traceback (most recent call last):
File "D:\python3.6\", line 4, in <module>
raise ValueError("a must be a number")
ValueError: a must be a number
Here we focus on raise located in the except block. Since we have manually raised the ValueError exception before it, it will be raised again when the raise statement is used again.
When a program that has not raised an exception uses a raised statement without a parameter, it throws a RuntimeError exception by default. For example:
try: a = input("Enter a number:") if(not ()): raise except RuntimeError as e: print("Rendered exception:",repr(e))
The program execution result is:
Enter a number: a
Throw an exception: RuntimeError('No active exception to reraise',)
Summarize
This is all about this article about the usage of raise in Python. For more related content on Python raise, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!