How to handle python exceptions

Source: Internet
Author: User
Tags finally block
This article provides a graphic explanation of the python exception handling method. python provides two very important functions to handle exceptions and errors in the running of python programs. You can use this function to debug python programs.

We can open idle --> F1 to view the document, which contains many exception types,

What is an exception?

An exception is an event that occurs during program execution and affects normal execution of the program.

Generally, an exception occurs when Python cannot process the program normally.

An exception is a Python object, indicating an error.

When a Python script exception occurs, we need to capture and process it; otherwise, the program will terminate the execution.

Exception handling

You can use the try/try T statement to catch exceptions.

The try/try T statement is used to detect errors in the try statement block, so that the try T statement can capture and handle exceptions.

If you don't want to end your program when an exception occurs, just capture it in try.

Syntax:

The following is a simpleTry... try t... elseSyntax:

try:

<语句> # Run other code

except <名字> :

<语句> # If the 'name' exception is thrown in the try part

except <名字> , <数据> :

<语句> # If the 'name' exception is thrown, obtain the additional data

else:

<语句> # If No exception occurs

The working principle of try is that after a try statement is started, python marks the context of the current program, so that when an exception occurs, you can return here and the try clause executes first, what will happen next depends on whether exceptions occur during execution.

If an exception occurs during statement execution after try, python will jump back to try and execute the first alias T clause that matches the exception. The exception processing is complete, the control flow uses the entire try statement (unless a new exception is thrown when an exception is handled ).

# If an exception occurs in the statement after try, but there is no matching limit T clause, the exception will be submitted to the try at the upper layer or to the upper layer of the program (this will end the program, and print the default error information ).

# If No exception occurs during the execution of the try clause, python will execute the statement after the else statement (if else exists) and then control the flow through the entire try statement.

Instance

The following is a simple example. it opens a file and writes content to the file without exception:

#!/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 results of the above program:

Written content in the file successfully

Instance

The following is a simple example. it opens a file and writes content to the file. However, the file has no write permission and an exception occurs:

#!/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"

Output results of the above program:

Error: can't find file or read data

Use Volume T without any exception type

You can use the following example without any exception types:

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.

In the preceding method, the try-retry T statement captures all exceptions. However, this is not a good method. we cannot use this program to identify specific exception information. Because it captures all exceptions. Handle T with multiple exception types

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

try:

You do your operations here;

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

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

The try-finally statement executes the final code no matter whether an exception occurs.

try:

<语句>

finally:

<语句> # Always run when you exit try

raise

Note:You can use the except t statement or finally statement, but the two 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 the write permission, the output is as follows:

Error: can't find file or read data

The 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 an exception is thrown in the try block, the finally block code is executed immediately.

After all statements in the finally block are executed, the exception is raised again and the blocks of code are executed.

The parameter content is different from the exception.

Abnormal parameters

An exception can contain parameters that can be used as output exception information parameters.

You can capture the exception parameters through the explain t statement, as shown below:

try:

You do your operations here;

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

except ExceptionType, Argument:

You can print value of Argument here...

Abnormal values received by variables are usually included in abnormal statements. In the form of tuples, a variable can receive one or more values.

Tuples usually contain error strings, error numbers, and error locations.

Instance

The following is an abnormal instance:

#!/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 exception

We can use the raise statement to trigger exceptions ourselves.

The raise syntax format is as follows:

raise [Exception [, args [, traceback]]]

In a statement, the Exception type (for example, NameError) parameter is an Exception parameter value. This parameter is optional. If this parameter is not provided, the exception parameter is "None ".

The last parameter is optional (rarely used in practice). if so, it is a trace exception object.

Instance

An exception can be a string, class, or object. The exception provided by the Python kernel is mostly instantiated classes, which are the parameters of a class instance.

Defining an exception is very simple, as shown below:

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:To capture exceptions, the "failed t" statement must use the same exception to throw class objects or strings.

For example, if we capture the above exceptions, the "handle T" statement is as follows:

try:

Business Logic here...

except "Invalid level!":

Exception handling here...

else:

Rest of the code here...

User-defined exception

By creating a new exception class, programs can name their own exceptions. Exceptions are typically inherited 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 limit T block statement after a custom 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 classes, you can trigger this exception as follows:

try:

raise Networkerror("Bad hostname")

except Networkerror,e:

print e.args

The above is a detailed description of the python exception handling method. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.