Home > Backend Development > Python Tutorial > Detailed graphic explanation of Python exception handling methods

Detailed graphic explanation of Python exception handling methods

高洛峰
Release: 2017-03-23 14:42:53
Original
1906 people have browsed it

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:

Detailed graphic explanation of Python exception handling methods

What is an exception?

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.

Exception handling

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

# ##If a 'name' exception is raised in the try part##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).

#If no exception occurs when the try clause is executed, python will execute the statement after the else statement (if there is an else), and then the control flow passes through the entire try statement.

Example

The following is a simple example, it opens a file, writes the content in the file, and no exception occurs:

#!/usr/bin/python

try:

fh

=

open("testfile", "w") 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"

fh.close()

Output result of the above program:

Written content in the file successfully

Example

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 dataUse 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

You can also use the same except statement to handle multiple exception messages, as shown below:

try

:

##You do your operations here;

........................

<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

try-finally statement will execute the last code regardless of whether an exception occurs.

try

:#

finally

:

#Exit

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

"Error: can\'t find file or read data"

If the opened file does not have writable permissions, the output will be as follows: Error: can't find

file

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.

Exception parameters

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;

..... ............

<p style="text-align: left;"><span style="color: #ff0000"><code>except 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.

Example

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

Call above function here.

##temp_convert(

"xyz "

);The execution result of the above program is as follows:

The argument does

not contain numbers##invalid literal

for

int() with base 10: 'xyz'Trigger exceptionWe can use the raise statement to trigger the exception ourselves

raise syntax format is as follows:

##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

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 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:

try

:

##raise Networkerror("Bad hostname")##except

Networkerror,e:

print

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template