Python provides two very important functions to handle exceptions and errors that occur when python programs are running. You can use this feature to debug python programs.
We can open idle-->F1 to view the document. There are many exception types in it, as shown in the figure:
An exception is an event that occurs during program execution and affects the normal execution of the program.
Generally, an exception occurs when Python cannot handle the program normally.
Exception is a Python object that represents an error.
When an exception occurs in a Python script, we need to catch and handle it, otherwise the program will terminate execution.
To catch exceptions, try/except statements can be used.
The try/except statement is used to detect errors in the try statement block, so that the except statement can capture the exception information and handle it.
If you don't want to end your program when an exception occurs, just catch it in try.
Grammar:
The following is the syntax of a simple try....except...else:
try
:
###Run other code
except
###except
##<statement> </statement>
#If a 'name' exception is raised, get additional data
else
:
#
#If not Exception occurs
The working principle of try is that when a try statement is started, python marks it in the context of the current program, so that when an exception occurs, it can return here, try The clause is executed first, and what happens next depends on whether an exception occurs during execution. If an exception occurs when the statement after try is executed, python will jump back to try and execute the first except clause matching the exception. After the exception is handled, the control flow will pass through the entire try statement (unless it is in A new exception is thrown when handling the exception).
#If an exception occurs in the statement after try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top level of the program (this will end the program and print the error Provincial error message).
try:
fh
open(
"testfile"
,
"w"
)
fh.write(
)##except
IOError:
print
"Error: can\'t find file or read data"
else
:
print
"Written content in the file successfully"
fh.close()
Output result of the above program:
Written content
in
the
file
successfully
The following is a simple example, it opens a file and writes the content in the file, but the file does not have write permission, and an exception occurred. :
#!/usr/bin/python
##try:
fh
=
open(
" testfile"
,
"r"
)
fh .write(
"This is my test file for exception handling!!"
)
except
IOError:
##print
"Error: can\'t find file or read data"
else:
print
"Written content in the file successfully"##The above program output result:
Error : can't find
file or
read data
Use except without any exception type
You can use except without any exception type, as shown in the following example:
try
:
You do your operations here;
.......... ............except
:
If there is
any
exception, then execute this block.
........................else
:
If there is
no exception then execute this block.
The try-except statement in the above way captures all exceptions that occur. But this is not a good way, we cannot identify specific abnormal information through this program. Because it catches all exceptions.
Use except with multiple exception types
try
:
<p style="text-align: left;"><span style="color: #ff0000"><code>except
(Exception1[, Exception2[,...ExceptionN]]]):
If there
is
any
exception
from
the given exception
list
,
##then execute this block.
##........................
else:
##If there is
no exception then execute this block.try-finally statement
:#
finally
:
raise
##Note: You can use the except statement or finally statement, but both cannot be used at the same time. The else statement cannot be used together with the finally statement
#!/usr/bin/python
try
:
fh
= open
(
"testfile"
,
"w"
)
fh.write(
"This is my test file for exception handling!!")
##finally
:
print
If the opened file does not have writable permissions, the output will be as follows:
Error: can't find
or
read dataThe same example can also be written as follows:
#!/usr/bin/python
try:
fh
open(
"testfile"
,
"w"
)
##
try
:
fh.write(
"This is my test file for exception handling!!"
)##finally
:
print
"Going to close the file"
#
fh.close( )
except IOError:
print
"Error: can\'t find file or read data"
When in try An exception is thrown in the block and the finally block code is executed immediately.
After all statements in the finally block are executed, the exception is raised again and the except block code is executed.
The content of the parameter is different from the exception.
An exception can take parameters, which can be used as output exception information parameters.
You can capture exception parameters through the except statement, as follows:
try
:
You do your operations here;
..... ............
ExceptionType, Argument:
You can
print
value of Argument here...
Exception values received by variables are usually included in the exception statement. Variables in the form of tuples can receive one or more values.
Tuples usually contain error strings, error numbers, and error locations.
The following is an example of a single exception:
#!/usr/bin/python
# Define a function here.
##def
temp_convert(var):
try
:
return
int(var)
##except
ValueError, Argument:
print
"The argument does not contain numbers\n", Argument
##temp_convert(
);
The execution result of the above program is as follows:
The argument does
not contain numbers
##invalid literal
int() with base
10
:
'xyz'
Trigger exception
We can use the raise statement to trigger the exception ourselves
##raise
[Exception [, args [, traceback]]]
Exception in the statement is the type of exception (for example, NameError) parameter is an exception parameter value. This parameter is optional, if not provided, the exception parameter is "None".
The last parameter is optional (rarely used in practice) and, if present, is the trace 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
"Invalid level!"
, level
# The code below to this would not be executed
# # if we raise the exception
Note: In order to catch exceptions, the "except" statement must use the same exception to throw the class object or string.
For example, if we catch the above exception, the "except" statement is as follows:try:
Business Logic here...
except
"Invalid level!" :
##Exception handling here...
else:
Rest of the code here...
User-Defined Exceptions
The following are examples related to RuntimeError. A class is created in the example. The base class is RuntimeError, which is used to output more information when an exception is triggered.
In the try statement block, the except block statement is executed 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):
.args
=
argAfter you define the above class, you can trigger the exception as follows:
:
##raise Networkerror(
"Bad hostname"
)
##except
e.args
The above is the detailed content of Detailed graphic explanation of Python exception handling methods. For more information, please follow other related articles on the PHP Chinese website!