Python exception handling and Exception Handling

Source: Internet
Author: User
Tags finally block

Python exception handling and Exception Handling

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.

1. Exception Handling: the Python tutorial on this site will be detailed.
2. Assertions: this Python tutorial will be detailed.

Python standard exception

Exception name Description
BaseException All abnormal base classes
SystemExit Interpreter request to exit
KeyboardInterrupt User interrupted execution (usually input ^ C)
Exception Base class with regular errors
StopIteration The iterator does not have more values.
GeneratorExit Generator exception to notify exit
SystemExit Python interpreter request to exit
StandardError All base classes with built-in standard exceptions
ArithmeticError Base classes with incorrect numeric calculation
FloatingPointError Floating Point Calculation Error
OverflowError The value operation exceeds the maximum limit.
ZeroDivisionError Except (or modulo) zero (all data types)
AssertionError Assertion statement failed
AttributeError The object does not have this property.
EOFError No built-in input, reaching the EOF tag
EnvironmentError Operating System Error base class
IOError Input/Output operation failed
OSError Operating System Error
WindowsError System Call failed
ImportError Import module/object failed
KeyboardInterrupt User interrupted execution (usually input ^ C)
LookupError Base class for invalid data query
IndexError This index is not found in the sequence)
KeyError The ing does not contain this key.
MemoryError Memory overflow error (not fatal for Python Interpreter)
NameError Object not declared/initialized (no attribute)
UnboundLocalError Access uninitialized local variables
ReferenceError Weak reference attempts to access garbage collection objects
RuntimeError General running errors
NotImplementedError Unimplemented Methods
SyntaxError Python syntax error
IndentationError Indentation Error
TabError Mix Tab and Space
SystemError General interpreter system error
TypeError Operation that is invalid for the Type
ValueError Invalid parameter passed in
UnicodeError Unicode errors
UnicodeDecodeError Unicode decoding error
UnicodeEncodeError Unicode Encoding Error
UnicodeTranslateError Unicode Conversion error
Warning Warning base class
DeprecationWarning Warning about discarded features
FutureWarning Warning about future semantic changes in Construction
OverflowWarning Old warning about automatic upgrade to long (long)
PendingDeprecationWarning Warning that features will be discarded
RuntimeWarning Warning of suspicious running behavior (runtime behavior)
SyntaxWarning Warning of suspicious syntax
UserWarning Warning generated by user code

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 simple try .... Else T... Else Syntax:

Copy codeThe Code is as follows:
Try:
<Statement> # Run other code
Country T <Name>:
<Statement> # If the 'name' exception is thrown in the try part
T <Name>, <DATA>:
<Statement> # If a 'name' exception is thrown, obtain additional data.
Else:
<Statement> # 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.

1. 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 ).

2. 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 ).

3. 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:
Copy codeThe Code is as follows:
#! /Usr/bin/python

Try:
Fh = open ("testfile", "w ")
Fh. write ("This is my test file for exception handling !! ")
Handle t 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:
Copy codeThe Code is as follows:
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:
Copy codeThe Code is as follows:
#! /Usr/bin/python

Try:
Fh = open ("testfile", "w ")
Fh. write ("This is my test file for exception handling !! ")
Handle t IOError:
Print "Error: can \'t find file or read data"
Else:
Print "Written content in the file successfully"

Output results of the above program:
Copy codeThe Code is as follows:
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:
Copy codeThe Code is as follows:
Try:
You do your operations here;
......................
Except t:
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:
Copy codeThe Code is as follows:
Try:
You do your operations here;
......................
Except T (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.
Copy codeThe Code is as follows:
Try:
<Statement>
Finally:
<Statement> # Always execute 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.

Instance
Copy codeThe Code is as follows:
#! /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:
Copy codeThe Code is as follows:
Error: can't find file or read data

The same example can also be written as follows:
Copy codeThe Code is 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 ()
Handle t 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:
Copy codeThe Code is as follows:
Try:
You do your operations here;
......................
Except t 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:
Copy codeThe Code is as follows:
#! /Usr/bin/python

# Define a function here.
Def temp_convert (var ):
Try:
Return int (var)
Failed t ValueError, Argument:
Print "The argument does not contain numbers \ n", Argument

# Call abve function here.
Temp_convert ("xyz ");

The execution result of the above program is as follows:
Copy codeThe Code 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:
Copy codeThe Code 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:
Copy codeThe Code is as follows:
Def functionName (level ):
If level <1:
Raise "Invalid level! ", Level
# The code below to this wocould not be executed
# If we raise the exception

Note: To capture exceptions, the "handle 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:
Copy codeThe Code is as follows:
Try:
Business Logic here...
Doesn t "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.
Copy codeThe Code is as follows:
Class Networkerror (RuntimeError ):
Def _ init _ (self, arg ):
Self. args = arg

After you define the above classes, you can trigger this exception as follows:
Copy codeThe Code is as follows:
Try:
Raise Networkerror ("Bad hostname ")
Failed t Networkerror, e:
Print e. args

Related Article

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.