python-08 异常

# 异常
# 8.1 异常是什么
# 异常对象来表示异常状态,并在遇到错误时引发异常。异常对象未被处理(或捕 获)时,程序将终止并显示一条错误消息

# 8.2 让事情沿着你指定的轨道出错

# 8.2.1 raise
#raise Exception

# 8.2.2 自定义的异常类
class SomeCustomException(Exception):
pass

# 8.3 捕获异常
'''
try:
x = int(input('Enter the first number:'))
y = int(input('Enter the second number:'))
print(x / y)
except ZeroDivisionError:
print('The second number can\'t be zero!')
'''
# 8.3.1 不用提供参数 raise
class MuffledCalculator:
muffled = False
def calc(self, expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffled:
print('Division by zero is illegal')
else:
raise

calculator = MuffledCalculator()
print(calculator.calc('10 / 2'))
calculator.muffled = True
print(calculator.calc('10 / 0'))

# 8.3.2 多个except子句
'''
try:
x = input('Enter the first number:')
y = input('Enter the second number:')
print(eval(x / y))
except ZeroDivisionError:
print('The second number can\'t be zero!')
except TypeError:
print('That wasn\'t a number, was it?')
'''

# 8.3.3 一箭双雕
'''
try:
x = input('Enter the first number:')
y = input('Enter the second number:')
print(eval(x / y))
except (ZeroDivisionError, TypeError, NameError):
print('Your number were bogus ...')
'''
# 8.3.4 捕获对象
'''
try:
x = input('Enter the first number:')
y = input('Enter the second number:')
print(eval(x / y))
except (ZeroDivisionError, TypeError, NameError) as e:
print(e)
'''
# 8.3.5 一网打尽
'''
try:
x = input('Enter the first number:')
y = input('Enter the second number:')
print(eval(x / y))
except:
print('Something wrong happened ...')
'''
#这样捕获所有的异常很危险,因为这不仅会隐藏你有心理准备的错误,还会隐藏你没有考虑过的错误

# 8.3.6 万事大吉时
'''
while True:
try:
x = int(input('Enter the first number:'))
y = int(input('Enter the second number:'))
print('x / y is', x / y)
except Exception as e:
print('Invalid input:', e)
print('Invalid input. Please try again.')
else:
break
'''
# 8.3.7 最后 finally
try:
1 / 0
except:
print('Unknown variable')
else:
print('That went well!')
finally:
print('Cleaning up.')

# 8.4 异常和函数
def faulty():
raise Exception('Something is wrong')

def ignore_exception():
faulty()

def handle_exception():
try:
faulty()
except:
print('Exception handled')
handle_exception()
#ignore_exception()

# 8.5 异常之禅 try/except或try/finally

# 8.6 不那么异常的情况 只发出警告 warning中的函数warn
from warnings import warn
print(warn('I have got a bad feeling about this.')) # 仅用于提醒,不会打断
print('111')

# 8.7 小结
# 异常对象:异常情况(如发生错误)是用异常对象表示的。对于异常情况,有多种处理方式;如果忽略,将导致程序终止。
# 引发异常:可使用raise语句来引发异常。它将一个异常类或异常实例作为参数,但你也可提供两个参数(异常和错误消息)。如果在except子句中调用raise时没有提供任何参数,它将重新引发该子句捕获的异常。
# 自定义的异常类:你可通过从Exception派生来创建自定义的异常。
# 捕获异常:要捕获异常,可在try语句中使用except子句。在except子句中,如果没有指定异常类,将捕获所有的异常。你可指定多个异常类,方法是将它们放在元组中。如果
# 向except提供两个参数,第二个参数将关联到异常对象。在同一条try/except语句中,可包含多个except子句,以便对不同的异常采取不同的措施。
# else子句:除except子句外,你还可使用else子句,它在主try块没有引发异常时执行。
# finally:要确保代码块(如清理代码)无论是否引发异常都将执行,可使用try/finally,并将代码块放在finally子句中。
# 异常和函数:在函数中引发异常时,异常将传播到调用函数的地方(对方法来说亦如此)。
# 警告:警告类似于异常,但(通常)只打印一条错误消息。你可指定警告类别,它们是Warning的子类。
'''
Exception 几乎所有的异常类都是从它派生而来的
AttributeError 引用属性或给它赋值失败时引发
OSError 操作系统不能执行指定的任务(如打开文件)时引发,有多个子类
IndexError 使用序列中不存在的索引时引发,为LookupError的子类
KeyError 使用映射中不存在的键时引发,为LookupError的子类
NameError 找不到名称(变量)时引发
SyntaxError 代码不正确时引发
TypeError 将内置操作或函数用于类型不正确的对象时引发
ValueError 将内置操作或函数用于这样的对象时引发:其类型正确但包含的值不合适
ZeroDivisionError 在除法或求模运算的第二个参数为零时引发
'''

猜你喜欢

转载自www.cnblogs.com/fuyouqiang/p/11844641.html