Python exception handling

高洛峰
Release: 2016-11-23 09:15:06
Original
1104 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.

Exception handling: This site’s Python tutorial will introduce it in detail.

Assertions: This site’s Python tutorial will introduce them in detail.

Python standard exception

Exception name

Description

BaseException Base class for all exceptions

SystemExit Interpreter request to exit

KeyboardInterrupt User interrupts execution (usually Enter^C)

Exception General Error base class

StopIteration The iterator has no more values ​​

GeneratorExit An exception occurs in the generator to notify the exit

SystemExit The Python interpreter requests to exit

StandardError Base class for all built-in standard exceptions

ArithmeticError Base class for all numerical calculation errors

FloatingPointError Floating point calculation error

OverflowError Numerical operation exceeds the maximum limit

ZeroDivisionError Division (or modulo) zero (all data types)

AssertionError Assertion statement failed

AttributeError The object does not have this attribute

EOFError No built-in input, EOF flag reached

EnvironmentError Base class for operating system errors

IOError Input/output operation failed

OSError Operating system error

WindowsError System call failed

ImportError Failed to import module/object

KeyboardInterrupt User interrupts execution (usually input ^C)

LookupError Base class for invalid data query

IndexError There is no such index in the sequence

KeyError There is no such key in the map

MemoryError Memory overflow error (for Python explanation) The device is not fatal)

NameError Undeclared/initialized object (no properties)

UnboundLocalError Accessing uninitialized local variable

ReferenceError Weak reference trying to access an object that has been garbage collected

RuntimeError General runtime Error

NotImplementedError Method not yet implemented

SyntaxError Python syntax error

IndentationError Indentation error

TabError Mixing tabs and spaces

SystemError General interpreter system error

TypeError Invalid operation on type

ValueError Invalid input Parameters

UnicodeError Unicode related errors

UnicodeDecodeError Unicode decoding error

UnicodeEncodeError Unicode encoding error

UnicodeTranslateError Unicode conversion error

Warning Warning base class

DeprecationWarning Warning about deprecated features

FutureWarning       Warning that the semantics of the construct will change in the future                                                                                                           out out out out out out out of                     out out. out out out off out out out out belonging out out belonging outft out Through out through out through out through out  through    ‐    to  ‐                                                     . ) Warning

SyntaxWarning Suspicious syntax warning

UserWarning Warning generated by user code

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.

Exceptions are Python objects that represent 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 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:

;:

Additional data

else:

          #If no 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 you can return here when an exception occurs. The try 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 processed again when handling the exception) throws a new 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 default 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()

The output of the above program:

Written content in the file successfully

Instance

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, an exception occurred:

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

The output of the above program:

Error: can't find file or read data

Use except without any exception type

You can use except without any exception type, as shown below:

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 above method The try-except statement catches 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 to bring 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;

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

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:

#Always executed when exiting try

raise

Note: You can use the except statement or the finally statement, but you cannot use both at the same time. The else statement cannot be used at the same time as the finally statement. write("This is my test file for exception handling!!")

finally:

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

If the open file does not have writable permissions , 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 in try block Throw an exception and execute the finally block code 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 parameters is different from exceptions.

Exception parameters

An exception can have parameters, which can be used as output exception information parameters.

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

try:

You do your operations here;

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

except ExceptionType, Argument:

You can print value of Argument here...

The exception value received by the variable is 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.

Instance

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 numbersn", 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'

To trigger an exception

we can use The raise statement triggers an exception by itself

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

Instance

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 be able to catch the exception, 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

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

The following is an example 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):

self.args = arg

After defining the above class, you can trigger the exception, As shown below:

try:

raise Networkerror("Bad hostname")

except Networkerror,e:

print e.args


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