异常

异常的继承

基类:Exception
先处理子类异常

class B(Exception):
    pass
class C(B):
    pass
class D(C):
    pass

for cls in [D,C,B]:
    try:
        raise cls()
    except D:       #先处理子类异常
        print("D")
    except C:
        print("C")
    except B:
        print("B")

输出:
D
C
B

一次处理多个异常
except (RuntimeError, TypeError, NameError):
    pass
引发异常
raise  NameError("hello")

输出:
Traceback (most recent call last):
File “11.py”, line 68, in
raise NameError(“hello”)
NameError: hello

raise  NameError

Traceback (most recent call last):
File “11.py”, line 69, in
raise NameError
NameError

不处理异常,重新引发异常
try:
    raise NameError("hello")
except NameError:
    print("An exception occured")
    raise

输出:
An exception occured
Traceback (most recent call last):
File “11.py”, line 71, in
raise NameError(“hello”)
NameError: hello

自定义异常

直接或间接继承Exception类

finally
try:
    raise NameError
finally:      #有无异常,必定执行
    print('Goodbye')
完整示例
def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("division by zero!")
    else:       #无异常执行
        print("result is", result)
    finally:    #有无异常,必定执行;定义 Clean-up
        print("executing finally clause")

# divide(2,1)
# divide(2,0)
# divide("hi",1)
divide(2,1)

输出:
result is 2.0
executing finally clause

divide(2,0)

输出:
division by zero!
executing finally clause

divide(“hi”,1)

输出:
executing finally clause
Traceback (most recent call last):
File “11.py”, line 91, in
divide(“hi”,1)
File “11.py”, line 80, in divide
result = x / y
TypeError: unsupported operand type(s) for /: ‘str’ and ‘int’

其他实例
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:    #文件不存在,捕捉此异常
    print(sys.exc_info())
    print(err)
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])   #打印异常类,如:<class 'FileNotFoundError'>
    raise

输出:
(<class ‘FileNotFoundError’>, FileNotFoundError(2, ‘No such file or directory’), <traceback object at 0x000001EAD831D588>)
[Errno 2] No such file or directory: ‘myfile.txt’
OS error: [Errno 2] No such file or directory: ‘myfile.txt’

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except OSError:
        print('cannot open', arg)
    else:   #放在else语句,防止非代码错误被隐藏
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()
try:
    raise Exception('spam', 'eggs')
except Exception as inst:
    print(type(inst))    # the exception instance
    print(inst.args)     # arguments stored in .args
    print(inst)          # __str__ allows args to be printed directly,
    # but may be overridden in exception subclasses
    x, y = inst.args     # unpack args
    print('x =', x)
    print('y =', y)

输出:
<class ‘Exception’>
(‘spam’, ‘eggs’)
(‘spam’, ‘eggs’)
x = spam
y = eggs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值