文章目录
8.1 异常是什么
Python使用异常对象来表示异常状态,并在遇到错误时引发异常。
8.2 自主引发异常
8.2.1 raise语句
>>> raise Exception
Traceback (most recent call last):
File "E:/Ppractice/Ppython/test/test.py", line 1, in <module>
raise Exception
Exception
8.2.2 自定义的异常类
class SomeCustomException(Exception):pass
8.3 捕获异常
try:
x = int(input('Enter the first number:'))
y = int(input('Enter the second numbrt:'))
print(x / y)
except ZeroDivisionError:
print("The second number can't be zero!")
8.3.1 多个except子句
try:
x = int(input('Enter the first number:'))
y = int(input('Enter the first number:'))
print(x / y)
except ZeroDivisionError:
print("The second number can't be zero!")
except TypeError:
print("That wasn't a number,was it?")
8.3.2 一个except子句捕获多种异常
try:
x = int(input('Enter the first number:'))
y = int(input('Enter the first number:'))
print(x / y)
except (ZeroDivisionError, TypeError, NameError):
print("Your numbers were bogus...")
8.3.3 捕获对象
需要让程序继续运行并记录错误时,这很有用。
try:
x = int(input('Enter the first number:'))
y = int(input('Enter the first number:'))
print(x / y)
except (ZeroDivisionError, TypeError) as e:
print(e)
8.3.4 最后
finally子句,可用于在发生异常时执行清理工作。
x = None
try:
x = 1/0
finally:
print('Cleaning up...')
del x
8.4 异常和函数
def faulty():
raise Exception('Something is wrong')
def handle_exception():
try:
faulty()
except:
print('Exception handled')
>>> handle_exception()
Exception handled