Detailed explanation of python exception handling methods

高洛峰
Release: 2017-03-21 11:57:41
Original
1447 people have browsed it

Exception

Exception (Exception) is an action taken outside the normal control flow due to exceptions, violations, errors, etc. of the program. It is generally divided into the following two stages:

1. Exception occurrence: An error is printed out after it occurs, which is called an unhandled exception. The default processing is to automatically output some debugging information and terminate the program.

2. Exception handling: If exceptions are handled explicitly through code, the program will not terminate and the fault tolerance of the program will be enhanced.

To put it bluntly, the purpose of exception handling is to make the program more executable and run smoothly; at the same time, it does not allow users to see embarrassing error messages. In layman’s terms, it means not to let users see embarrassing error messages. Users see the Yellow Pages.

Exceptions can be viewed through the exception type (Exception) in python3.

Common exceptions:

AttributeError  #试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
IOError  #输入/输出异常;基本上是无法打开文件
ImportError  #无法引入模块或包;基本上是路径问题或名称错误
IndentationError  #语法错误(的子类) ;代码没有正确对齐
IndexError  #下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError  #试图访问字典里不存在的键
KeyboardInterrupt  #Ctrl+C被按下
NameError  #使用一个还未被赋予对象的变量
SyntaxError  #Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
TypeError  #传入对象类型与要求的不符合
UnboundLocalError  #试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它
ValueError #传入一个调用者不期望的值,即使值的类型是正确的
Copy after login

More exceptions:

ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError
Copy after login

Exception handling

Python3 provides a try statement to handle exceptions, the format is:

try:
    print('#先运行别指定的代码')
except Exception as e:  #所有的异常都继承至Exception类,可以捕获任意异常
    print(e)  #可以获取异常e
    print('#如果发生了异常,执行异常处理')
else:
    print('#如果主代码块没有异常发生并执行完后,则继续往下执行')
Copy after login

Or:

try:
    print('#先运行特定的代码')
except Exception as e:
    print('#捕获对应的异常并处理之')
finally:
    print('#不管异常与否,最终都会执行')
Copy after login
dic = ["English", 'Chinese']
try:
    dic[10]
except IndexError as e:
    print(e)
Copy after login
s1 = 'hello'
try:
    int(s1)
except ValueError as e:
    print(e)
Copy after login

When an unspecified exception is encountered, an error will be reported:

# 未捕获到异常,程序直接报错
 
s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
Copy after login

When multiple exceptions are to be handled, you can also write like this:

except ( AttributeError,NameError ) as e:
    print(e)
    print('#这是捕获多个类型异常的语法')
Copy after login

Although Exception can catch any exception, exceptions for special processing or reminders need to be defined first, and finally define Exception to ensure the normal operation of the program. Therefore, the following writing method is also very commonly used:

s1 = 'hello'
try:
    int(s1)
except KeyError as e:
    print('键错误')
except IndexError as e:
    print('索引错误')
except Exception as e:
    print('错误')
Copy after login

raise statement actively triggers exceptions. In python3, you can use the raise statement to throw a general exception type (Exception), as follows:

try:
    raise Exception('错误了...') #这是主动引发一个异常
except Exception as e:
    print(e)
Copy after login

In python3 You can also customize exceptions by creating a class that inherits from a common exception type (Exception):

#关于raise语句,还有:
class Myerror(Exception):
    def __init__(self,msg):
        self.msg = msg
 
    def __str__(self):  # 以字符串格式输出
        return self.msg
 
 
try:
    raise Myerror('错误')
except Exception as f:
    print(f)
Copy after login

The above is the detailed content of Detailed explanation of python exception handling methods. For more information, please follow other related articles on the PHP Chinese website!

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