Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python exception handling


May 10, 2021 Python2


Table of contents


Python exception handling

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

  • Exception handling: This site Python tutorial will be detailed.
  • Assertions: This chapter, the Python tutorial, is detailed.

Python standard exception

The name of the exception Describe
BaseException The base class for all exceptions
SystemExit The interpreter requests an exit
KeyboardInterrupt User interrupt execution (usually input sC)
Exception The base class for a general error
StopIteration The iterator has no more values
GeneratorExit An exception occurred in the generator to notify the exit
StandardError The base class for all built-in standard exceptions
ArithmeticError The base class for all numeric calculation errors
FloatingPointError The floating point is miscalculated
OverflowError The numeric operation exceeds the maximum limit
ZeroDivisionError Except (or mold) zero (all data types)
AssertionError The assertion statement failed
AttributeError The object does not have this property
EOFError There is no built-in input to reach the EOF tag
EnvironmentError The base class for operating system errors
IOError The input/output operation failed
OSError The operating system is wrong
WindowsError The system call failed
ImportError The import of modules/objects failed
LookupError The base class of an invalid data query
IndexError There is no index in the sequence
KeyError This key is not in the map
MemoryError Memory overflow errors (not fatal for Python interpreters)
NameError Unrealized/initialized object (no properties)
UnboundLocalError Access local variables that are not initialized
ReferenceError Weak reference attempts to access an object that has been garbage collected
RuntimeError General run-time errors
NotImplementedError Methods that have not yet been implemented
SyntaxError Python syntax error
IndentationError Indentation error
TabError Tabs are mixed with spaces
SystemError General interpreter system error
TypeError An action that is not valid for the type
ValueError An invalid argument is passed in
UnicodeError Unicode-related errors
UnicodeDecodeError Error when Unicode decoded
UnicodeEncodeError Unicode encoded incorrectly
UnicodeTranslateError Unicode was converted incorrectly
Warning The base class of the warning
DeprecationWarning Warnings about deprecated features
FutureWarning Warnings about future semantic changes in construction
OverflowWarning The old warning about automatically promoting to long
PendingDeprecationWarning Warning that features will be discarded
RuntimeWarning A warning of suspicious runtime behavior
SyntaxWarning Warning of suspicious syntax
UserWarning A 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.

In general, an exception occurs when Python does not handle the program properly.

The exception is a Python object, indicating an error.

When an exception occurs to the Python script, we need to catch and process it, or the program will terminate execution.


Exception handling

Catching exceptions can use the try/except statement.

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

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

Grammar:

Here's a simple try.... e xcept... The syntax of else:

try:
<语句>        #运行别的代码
except <名字>:
<语句>        #如果在try部份引发了'名字'异常
except <名字>,<数据>:
<语句>        #如果引发了'名字'异常,获得附加的数据
else:
<语句>        #如果没有异常发生

Try works by marking Python in the context of the current program when a try statement is started, so that when an exception appears, it can come back here, the try clause executes first, and what happens next depends on whether the exception occurs when it is executed.

  • If an exception occurs when a statement after try executes, Python jumps back to try and executes the first except clause that matches the exception, and when the exception is processed, the control flow passes through the entire try statement (unless a new exception is thrown when the exception is handled).
  • If an exception occurs in the statement after try, but there is no matching except clause, the exception is submitted to the upper try, or to the top of the program (which ends the program and prints the default error message).
  • If no exception occurs when the try clause is executed, Python executes the statement after the else statement, if any, and then controls the flow through the entire try statement.

Instance

Here's a simple example of opening a file in which the contents are written and no exceptions occur:

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

 Written content in the file successfully

Instance

Here's a simple example of a file that opens a file in which the contents are written, but the file does not have write permissions, and an 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"

The above program output results:

Error: can't find file or read data

Use except without any exception type

You can use excelpt without any exception type, as follows:

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 try-except statement above captures all the exceptions that occur. B ut this is not a good way, we can not identify specific abnormal information through the program. B ecause it catches all the exceptions.


Use except with multiple exception types

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

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 regardless of whether an exception occurs or not.

try:
<语句>
finally:
<语句>    #退出try时总会执行
raise

Note: You can use the except statement or the final statement, but they cannot be used at the same time. The else statement cannot be used in the same time as the final statement

Instance

#!/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 open file does not have writeable permissions, the output looks like this:

Error: can't find file or read data

The same example can 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 final block code is executed immediately.

After all the statements in the final block are executed, the exception is raised again and the except block code is executed.

The contents of the argument are different from the exception.


The parameters of the exception

An exception can be brought with it and can be used as an exception information parameter for the output.

You can catch the parameters of the exception with the except statement, as follows:

try:
   You do your operations here;
   ......................
except ExceptionType, Argument:
   You can print value of Argument here...

The outlier values received by the variable are usually contained in the statement of the exception. Variables can receive one or more values in a meta-group form.

A group usually contains an error string, an error number, and an error location.

Instance

The following are instances of a single exception:

#!/usr/bin/python

# 定义函数
def temp_convert(var):
   try:
      return int(var)
   except ValueError, Argument:
      print "The argument does not contain numbers\n", Argument

# 调用函数
temp_convert("xyz");

The results of the above procedures are as follows:

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

Trigger an exception

We can use the raise statement to trigger the exception ourselves

The raise syntax format is as follows:

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

Exception in a statement is an exception type (for example, NameError) argument is an exception parameter value. This parameter is optional and, if not provided, the exception's argument is None.

The last argument is optional (rarely used in practice) and, if present, is a tracking exception object.

Instance

An exception can be a string, class, or object. Most of the exceptions provided by Python's kernel are instantiated classes, which are parameters of an instance of a class.

Defining an exception is as simple as this:

def functionName( level ):
    if level < 1:
        raise Exception("Invalid level!", level)
        # 触发异常后,后面的代码就不会再执行

Note: In order to be able to catch exceptions, the "except" statement must use the same exception to throw class objects or strings.

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

try:
   Business Logic here...
except "Invalid level!":
   Exception handling here...
else:
   Rest of the code here...

A user-defined exception

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

The following is an instance related to RuntimeError, in which a class is created, based on a RuntimeError, that outputs more information when an exception is triggered.

In the try statement block, the user-defined exception executes the except block statement after the variable e is an instance used to create the Networkerror class.

class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg

After you define the class above, you can trigger the exception as follows:

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

Exception handling code execution instructions:

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

#This is note foe exception

try:
  code    #需要判断是否会抛出异常的代码,如果没有异常处理,python会直接停止执行程序

except:  #这里会捕捉到上面代码中的异常,并根据异常抛出异常处理信息
#except ExceptionName,args:    #同时也可以接受异常名称和参数,针对不同形式的异常做处理

  code  #这里执行异常处理的相关代码,打印输出等


else#如果没有异常则执行else

  code  #try部分被正常执行后执行的代码

finally:
  code  #退出try语句块总会执行的程序



#函数中做异常检测
def try_exception(num):
  try:
    return int(num)
  except ValueError,arg:
    print arg,"is not a number"
  else:
    print "this is a number inputs"


try_exception('xxx')

#输出异常值
Invalide literal for int() with base 10: 'xxx' is not a number