Python exception handling

Python provides two very important features to handle exceptions and errors that occur when Python programs are running. You can use this feature to debug python programs.

  • Exception handling: This site Python tutorial will be introduced.
  • Assertions: This site will be introduced in detail in the Python tutorial.

Python standard exception

Exception name Description
BaseException base class for all exceptions
SystemExitInterpreter request to exit
KeyboardInterrupt User interrupt execution (usually input ^C)
Exceptionbase class for general errors
StopIteration iterator has no more values
GeneratorExit generator has an exception to notify the exit
StandardError The base class for all built-in standard exceptions
ArithmeticError The base class for all numerical calculation errors
FloatingPointError Floating point calculation error
OverflowError Numerical operations exceed the maximum limit
ZeroDivisionError divide (or modulo) zero (all data types)
AssertionError Assertion statement failed
AttributeError Object does not have this attribute
EOFError No built-in input, reach EOF tag
EnvironmentError base class for operating system error
IOError Input/Output operation failed
OSError Operating system error
WindowsError System call failed
ImportError Failed to import module/object
LookupError base class for invalid data queries
IndexError There is no such index in the sequence (index)
KeyError does not have this key in the mapping
MemoryError Memory Overrun Error (not fatal for Python interpreter)
NameError Undeclared/initialized object (no attributes)
UnboundLocalError Access uninitialized local variables
ReferenceError Weak reference attempts to access an object that has been garbage collected
RuntimeError General runtime error
NotImplementedError Not implemented method
SyntaxErrorPython syntax error
IndentationError Indentation Error
TabError Tab and Space Mix
SystemError General interpreter system error
TypeError Invalid operation on type
ValueError Incoming invalid parameters
UnicodeError Unicode related errors
UnicodeDecodeError Error in Unicode decoding
UnicodeEncodeError Unicode encoding error
UnicodeTranslateError Unicode conversion error
Warning base class for warning
DeprecationWarning Warning about deprecated features
FutureWarning warning about constructing future semantics
OverflowWarning Old warning about automatic promotion to long (long)
PendingDeprecationWarning Warning about features will be discarded
RuntimeWarning Troubleshooting of suspicious runtime behavior
SyntaxWarning Warning of suspicious syntax
UserWarning User Code Generated Warning

What is an exception?

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

In general, an exception occurs when Python cannot handle the program normally.

The exception is a Python object and represents an error.

When an exception occurs in a Python script, we need to capture it, otherwise the program will terminate execution.


Exception handling

To catch exceptions, use the try/except statement.

The try/except statement is used to detect errors in the try block, allowing the except statement to catch exception information and process it.

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

grammar:

The following is a simple try....except...else syntax:

try:
<statement> #running other code 
except <name>:
<statement> #if it raises in the try section Name 'Exception
except <name>,<data>:< /span>
<statement> #if a 'name' exception is raised, Get additional data
else:
<statement> #if no exceptions occur 

The working principle of try is that when starting a try statement, python marks in the context of the current program, so that when the exception occurs, it can be returned here, the try clause is executed first, and what happens next depends on the execution time. Whether an exception has occurred.

  • If an exception occurs when the statement after the try is executed, python jumps back to try and executes the first exception clause that matches the exception. After the exception is processed, the control flow passes through the entire try statement (unless new exceptions are raised when the exception is handled). Anomaly).
  • If an exception occurs in the statement after the try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (this will end the program, and print the missing Provincial error message).
  • If no exception occurs during the execution of the try clause, python will execute the statement after the else statement (if there is an else), and then control the flow through the entire try statement.

Instance

The following is a simple example that opens a file and writes the contents of the file without exception:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

try:
    Fh = open("testfile", "w"< Span class="pun">)
    Fh.write("This is a test file for testing exceptions!!")
except IOError :
    print "Error: File not found or failed to read file"< /span>
        
        
        else:
    print "Content was successfully written to the file"
    Fh.close()

The above program output:

$ python test.py
Content was successfully written to the file
$ cat testfile # View written content
This is a test file for testing exceptions!!

Instance

The following is a simple example, it opens a file, the content in the file is written to the content, but the file has no write permission, an exception occurs:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

try:
    Fh = open("testfile", "w"< Span class="pun">)
    Fh.write("This is a test file for testing exceptions!!")
except IOError :
    print "Error: File not found or failed to read file"< /span>
else:
    print "Content was successfully written to the file"
    Fh.close()

Before the code is executed, for the convenience of testing, we can first remove the write permission of the testfile, the command is as follows:

chmod -w testfile< /span>

Execute the above code again:

$ python test.py
Error:  Failed to find file or read file

Use except without any exception type

You can use except without any exception type, as in the following example:

try:
    Normal operation
   ........................
except:
    An exception occurred, execute this code
   ........................
else:
    Execute this code if there are no exceptions

The above-style try-except statement captures all occurrences of exceptions. But this is not a good way, we can not identify specific exception information through the program. Because it captures all the exceptions.


Use exception with multiple exception types

You can also use the same except statement to handle multiple exceptions, as follows:

try:
    Normal operation
   ........................
except(Exception1[, Exception2[,...< Span class="typ">ExceptionN]]]):
   One ​​of the above exceptions occurred, execute this code
   ........................
else:
    Execute this code if there are no exceptions

try-finally statement

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

try:
<Statement>
finally:
<Statement> #Will always execute when you exit try
raise

Instance

#!/usr/bin/python
# -*- coding: UTF-8 -*-

try:
fh = open("testfile", "w")
fh.write("This is a test file for testing exceptions!!")
finally:
print "Error: Failed to find file or read file"

If the open file does not have write access, the output looks like this:

$ python test.py
Error: Failed to find file or read file

The same example can also be written as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

try:
fh = open("testfile", "w")
try:
fh.write("This is a test file for testing exceptions!!")
finally:
print "关闭文件"
fh.close()
except IOError:
print "Error: Failed to find file or read file"

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 fired again and the except block code is executed.

The content of the parameter is different from the exception.


Exception parameter

An exception can be parameterized and can be used as an output exception parameter.

You can catch exception parameters with the exception statement as follows:

try:
     Normal operation
    ........................
except ExceptionType , Argument:
     You can output here Argument values...

The exception value received by the variable is usually included in the statement of the exception. A variable can receive one or more values in a tuple's form.

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

Instance

The following is an example of a single exception:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Defining function
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "Parameter does not contain a number\n", Argument

# call function
temp_convert("xyz");

The above program execution results are as follows:

$ python test.py
Parameter does not contain a number
invalid literal for int() with base 10: 'xyz'

Trigger exception

We can use the raise statement to trigger an exception ourselves

The

raise syntax is as follows:

raise [Exception [, args < /span>[, traceback]]]

In the statement Exception is any type of exception (for example, NameError) parameter standard exception, args is the exception parameter provided by itself.

The last parameter is optional (usually used in practice) and, if it exists, is to track exception objects.

Instance

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

Defining an exception is very simple, as shown below:

def functionName( level ):
    if level < 1:
        raise Exception ("Invalid level!", level)
        # After the exception is triggered, the following code will no longer execute

Note: In order to be able to catch exceptions, the "except" statement must throw the class object or string with the same exception.

For example, we capture the above exception, the "except" statement looks like this:

try:
    
    
   Normal logic
except Exception,err:
Trigger a custom exception
else:
Remaining code

Instance

#!/usr/bin/python
# -*- coding: UTF-8 -*- 

# Defining function
def mye( level ):
if level < 1:
raise Exception,"Invalid level!"
# After the exception is triggered, the following code will no longer executetry:
mye(0) # Trigger exception
except Exception,err:
print 1,err
else:
print 2

Execute the above code, the output is:

$ python test.py
1 Invalid Level!

User-defined exceptions

By creating a new exception class, programs can name their own exceptions. Exceptions should be typically inherited from the Exception class, either directly or indirectly.

The following is an example related to RuntimeError. A class is created in the instance. The base class is RuntimeError, which is used to output more information when the exception is triggered.

In the try block, the user-defined exception is executed after the exception block statement, 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 class, you can trigger the exception as follows:

try:
    raise Networkerror ("Bad hostname")
except Networkerror ,e:
    print e.args





javacodegeeks is optimized for learning.© javacodegeeks
All Right Reserved and you agree to have read and accepted our term and condition.