Python getting started example series 22 errors and exceptions
What is an exception?
In general, an exception occurs when Python cannot handle the program properly.
An exception is a Python object that represents an error. For example, an exception occurs when reading a file that does not exist, and an exception occurs when 20 is divided by 0.
When an exception occurs in a Python script, we need to catch and handle it, otherwise the program will terminate execution.
exception handling
To catch exceptions, you can use the try/except statement.
The try / exception statement is used to detect errors in the try statement block, so that the exception statement can catch exception information and handle it.
If you don't want to end your program when an exception occurs, just catch it in try.
Syntax:
The following is a simple try except... Else syntax:
try:
<sentence> #Run other code
except <name>:
<sentence> #If in try Partially triggered'name'abnormal
except <name>,<data>:
<sentence> #If triggered'name'Exception, get additional data
else:
<sentence> #If no exception occurs
The working principle of try is that after starting a try statement, python marks it in the context of the current program, so that it can return here when an exception occurs. The try clause is executed first. What happens next depends on whether an exception occurs during execution.
- If an exception occurs during the execution of the statement after the try, python will jump back to the try and execute the first exception clause matching the exception. After the exception is handled, the control flow will pass through the whole try statement (unless a new exception is thrown when handling the exception).
- If an exception occurs in the statement after the try, but there is no matching except clause, the exception will be submitted to the upper try or to the top of the program (this will end the program and print the default error message).
- If no exception occurs during the execution of the try clause, python will execute the statement after the else statement (if there is else), and then control the flow through the whole try statement.
The following is a simple example. It opens a file and writes the contents in the file without exception:
try:
fh = open("testfile", "w")
fh.write("Test exception")
except IOError:
print("Error: File not found or failed to read")
else:
print( "Content written to file successfully")
fh.close()
Output results of the above program:Content written to file successfully
Use except without any exception types
You can use except without any exception type, as shown in the following example:
try:
Normal operation
......................
except:
If an exception occurs, execute this code
......................
else:
If there are no exceptions, execute this code
In the above way, the try except statement captures all exceptions that occur. But this is not a good way. We can't identify specific exception information through this program. Because it catches all exceptions.
Use exception with multiple exception types
You can also use the same except statement to handle multiple exception information, as shown below:
try:
Normal operation
......................
except(Exception1[, Exception2[,...ExceptionN]]):
If one of the above exceptions occurs, execute this code
......................
else:
If there are no exceptions, execute this code
Try finally statement
The try finally statement executes the last code whether or not an exception occurs.
try:
<sentence>
finally:
<sentence> #sign out try Always execute when
raise
example
try:
fh = open("testfile", "w")
fh.write("This is a test file for testing exceptions!!")
finally:
print("Error: File not found or failed to read")
Abnormal parameters
An exception can take parameters, which can be used as the output exception information parameters.
You can use the except statement to catch the parameters of the exception, as shown below:
try:
Normal operation
......................
except ExceptionType as Argument:
You can output here Argument Value of...
The exception value received by the variable is usually contained in the exception statement. Variables can receive one or more values in the form of tuples.
Tuples usually contain error strings, error numbers, and error locations.
The following are examples of a single exception:
# Define function
def temp_convert(var):
try:
return int(var)
except ValueError as Argument:
print("The parameter does not contain a number\n", Argument)
# Call function
temp_convert("xyz")
The results of the above procedures are as follows:
The parameter does not contain a number
invalid literal for int() with base 10: 'xyz'
Trigger exception
We can use the raise statement to trigger the exception ourselves
The raise syntax format is as follows:
raise [Exception [, args [, traceback]]]
In the statement, Exception is the type of Exception (for example, NameError) parameter, any of the standard exceptions, and args is the Exception parameter provided by itself.
The last parameter is optional (rarely used in practice) and, if present, tracks the exception object.
example
An exception can be a string, class, or object. Most of the exceptions provided by the Python kernel are instantiated classes, which are parameters of an instance of a class.
Defining an exception is very simple, as follows:
def functionName( level ):
if level < 1:
raise Exception("Invalid level!", level)
# After the exception is triggered, the following code will not be executed
try:
functionName(0) # Trigger exception
except Exception as err:
print(1,err)
else:
print(2)
Note: in order to catch exceptions, the "except" statement must throw class objects or strings with the same exception.
Execute the above code and the output result is:
1 ('Invalid level!', 0)
User defined exception
Programs can name their own exceptions by creating a new Exception class. Exceptions should typically inherit from the Exception class, either directly or indirectly.
The following is an instance related to RuntimeError. A class is created in the instance. The base class is RuntimeError, which is used to output more information when an exception is triggered.
In the try statement block, execute the exception block statement after the user-defined exception. The variable e is used to create an instance of the Networkerror class.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
## After you define the above class, you can trigger the exception, as shown below:
try:
raise Networkerror("Bad hostname")
except Networkerror as e:
print(e.args)
Python built-in exception:
https://docs.python.org/zh-cn/3/library/exceptions.html#bltin-exceptions
REF
https://docs.python.org/zh-cn/3/tutorial/errors.html
https://www.runoob.com/python/python-exceptions.html