详解python异常处理方法

python教程评论945 views阅读模式

异常

异常(Exception)是因为程序的例外、违例、出错等情况而在正常控制流以外采取的行为,一般分为如下两个阶段:

1.异常发生:一个错误发生后被打印出来,称为未处理异常,而默认的处理则是自动输出一些调试信息并终止程序运行。

2.异常处理:通过代码明确地处理异常,则程序不会终止运行,并增强程序的容错性。

说白了,异常处理的目的就是为了是程序的可执行性更高,能顺利的运行下去;同时不让用户看到难堪的错误信息,通俗来说就是不让用户看见大黄页。

可以通过python3中的异常类型(Exception)查看异常。

常见的异常:

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

更多的异常:

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

异常处理

python3中提供try语句处理异常,格式为:

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

或者:

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

而当遇到非指定异常,则会报错:

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

当要处理多个异常时也可以这样写:

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

虽然Exception可以捕获任意异常,但对于特殊处理或提醒的异常需要先定义,最后定义Exception来确保程序正常运行。所以下面这种写法也很常用:

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

raise语句主动触发异常,python3中可以利用raise语句抛出一个通用异常类型(Exception),具体如下:

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

python3中也可以通过创建继承至通用异常类型(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)

以上就是详解python异常处理方法的详细内容,更多请关注php教程其它相关文章!

企鹅博客
  • 本文由 发表于 2020年5月17日 08:14:56
  • 转载请务必保留本文链接:https://www.qieseo.com/341075.html

发表评论