Exception handling
You can use the Try/except statement to catch an exception.
The try/except statement is used to detect errors in a try statement block, allowing the except statement to catch exception information and handle it.
Here's the syntax:
1 Try:2< statements >#Run another code3 except< name >:4< statements >#if the ' name ' exception is thrown in the try section5 except< name >,< data >:6< statements >#if the ' name ' exception is thrown, get additional data7 Else:8< statements >#If no exception occurs
Try works by starting a try statement, and Python is tagged in the context of the current program so that when an exception occurs, it can go back here, the TRY clause executes first, and what happens next depends on whether an exception occurs at execution time.
- If an exception occurs when the statement after the try is executed, Python jumps back to the try and executes the first except clause that matches the exception, and the control flow passes through the entire try statement (unless a new exception is thrown when the exception is handled).
- 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 when the TRY clause executes, Python executes the statement after the Else statement (if there is else), and then the control flow passes through the entire try statement.
Use except without any exception type
You can use except without any exception type, as in the following example:
1 Try : 2 The normal operation 3 ... ........... 4 except : 5 An exception occurred, execute this code 6 ............. 7 Else : 8 If there is no exception to execute this piece of code
The try-except statement above captures all occurrences of the exception. But this is not a good way to identify specific exception information through the program. Because it catches all the exceptions.
Using except with multiple exception types
You can also use the same except statement to handle multiple exception information, as follows:
1 Try : 2 The normal operation 3 ... ........... 4 except (exception1[, exception2[,... Exceptionn]]):5 occurrence of one of the above multiple exceptions, execute this code 6 ...................... 7 Else : 8 If there is no exception to execute this piece of code
try-finally statements
The try-finally statement executes the final code regardless of whether an exception occurs.
1 Try : 2 < statements >3finally:4 < statements > # 5 raise is always executed when exiting a try
Executes the finally block code immediately when an exception is thrown in the try block.
After all the statements in the finally block are executed, the exception is triggered again, and the except block code is executed.
The contents of the parameter differ from the exception.
parameter of the exception
An exception can take a parameter that can be used as the output exception information parameter.
You can use the except statement to catch the parameters of the exception, as follows:
1 Try : 2 The normal operation 3 ... ........... 4 except Exceptiontype, Argument: 5 You can output the value of Argument in this ...
The exception value that the variable receives is usually contained in the exception's statement. In a tuple's form, a variable can receive one or more values.
Tuples typically contain error strings, error numbers, and error locations.
Triggering an exception
We can use the raise statement to trigger the exception ourselves
The raise syntax format is as follows:
Raise [Exception [, Args [, Traceback]]
The Exception statement is either of the exception type (for example, nameerror) parameter standard exception, and args is a self-supplied exception parameter.
The last parameter is optional (rarely used in practice) and, if present, is the tracking exception object.
Note: to be able to catch exceptions, the "except" statement must have the same exception to throw the class object or string.
For example, we capture the above exception, and the "except" statement looks like this:
1 Try : 2 Normal Logic 3except exception,err:4 trigger Custom Exception 5 Else : 6 The rest of the code
User-defined exceptions
By creating a new Exception class, programs can name their own exceptions. Exceptions should be typical of inheriting from the exception class, either directly or indirectly.
The following is an example of a runtimeerror-related instance in which a class is created and the base class is RuntimeError, which is used to output more information when the exception is triggered.
In the TRY statement block, after the user-defined exception executes the EXCEPT block statement, the variable e is used to create an instance of the Networkerror class.
1 class Networkerror (runtimeerror): 2 def __init__ (Self, arg): 3 Self.args = arg
After you define the above class, you can trigger the exception as follows:
Try : Raise Networkerror ("badhostname")except networkerror,e: Print E.args
Getting Started with Python (i) Exception handling