Python exception handling instance details

Source: Internet
Author: User
Python provides two very important functions (Assertions and Assertions) to handle exceptions and errors in the running of python programs, you can use this function to catch exceptions in python programs. 1. 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.
II. 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.

Exception syntax:
The following is a simple try... example T... else syntax:

The code is as follows:

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.

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

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

The code is as follows:

Written content in the file successfully


Exception handling instance 2:
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:

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

The code is as follows:

Error: can't find file or read data

3. use volume t without any exception type

You can use the following example without any exception types:

The 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.
4. Using the handle T with multiple exception types
You can also use the same except t statement to handle multiple exceptions, as shown below:

The 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.


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

The code is as follows:

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.

Try-finally Usage example:

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

The code is as follows:

Error: can't find file or read data


The same example can also be written as follows:

The 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.

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

The 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.
The following is an abnormal instance:

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

The code is as follows:

The argument does not contain numbers
Invalid literal for int () with base 10: 'XYZ'


Use raise to trigger an exception:
We can use the raise statement to trigger exceptions ourselves.

The raise syntax format is as follows:

The 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.
Raise Usage example:
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:

The 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 "expect 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:

The code is as follows:

Try:
Business Logic here...
Doesn t "Invalid level! ":
Exception handling here...
Else:
Rest of the code here...

VII. user-defined exception instance
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.

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

The code is as follows:

Try:
Raise Networkerror ("Bad hostname ")
Failed T Networkerror, e:
Print e. args


Appendix: python Standard Exception
Base‑tiona: all abnormal base classes
SystemExitb python: interpreter request to exit
KeyboardInterruptc: User interrupt execution (usually input ^ C)
Exceptiond: base class with regular errors
StopIteratione: the iterator does not have more values.
GeneratorExita: the generator (generator) generates an exception to notify the exit.
SystemExith: The Python interpreter requests to exit
StandardErrorg: all base classes with built-in standard exceptions
ArithmeticErrord: base class with incorrect numeric calculation
FloatingPointErrord: Floating point calculation error
OverflowError: the numeric operation exceeds the maximum limit.
ZeroDivisionError: Divide (or modulo) zero (all data types)
AssertionErrord: the asserted statement fails.
AttributeError: the object does not have this attribute.
EOFError: no built-in input, reaching the EOF tag
EnvironmentErrord: base class with an operating system error
IOError: The input/output operation fails.
OSErrord: Operating system error
WindowsErrorh Windows: System call failed
ImportError: import module/object failed
KeyboardInterruptf: User interrupt execution (usually input ^ C)
LookupErrord: 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: Undeclared/initialized object (no attribute)
UnboundLocalErrorh: access to uninitialized local variables
ReferenceErrore: Weak reference attempts to access garbage collection objects
RuntimeError: a general running error
NotImplementedErrord: unimplemented method
SyntaxError: Python syntax error
IndentationErrorg: indentation error
TabErrorg: mix Tab and space
SystemError common interpreter system error
TypeError: operation that is invalid for the type
ValueError: the input parameter is invalid.
UnicodeErrorh: Unicode errors
UnicodeDecodeErrori: Unicode decoding error
UnicodeEncodeErrori: Unicode encoding error
UnicodeTranslateErrorf: Unicode conversion error
Warningj: Warning Base Class
DeprecationWarningj: Warning about discarded features
FutureWarningi: warning about future semantic changes in construction
OverflowWarningk: old warning about automatic escalation to long integer (long)
PendingDeprecationWarningi: Warning that features will be discarded
RuntimeWarningj: Warning of suspicious runtime behavior (runtime behavior)
SyntaxWarningj: Warning of suspicious syntax
UserWarningj: Warning generated by user code

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.