python异常处理整理

# 自定义异常类,采用基本异常类继承
class Test_case_error(Exception):pass

def hello(filename):
    if filename == 'hello':
        raise NameError('input name error')
    if filename == 'haha':
        raise KeyError('can\'t pharse number')
    if filename == 'exception':
        raise Exception('you can try it')
    if filename == '1':
        raise Test_case_error('hahahha')

# try 中抛出的异常由except 来处理,由except处理异常后,程序不会中断会继续执行
try:
    hello(filename)
except Test_case_error:
    print('hello')

# 通过标识打开和关闭异常处理,可使用raise 主动抛出异常
class MuffledCalculator:
    def __init__(self,muffled):
        self.muffled = muffled
    def calc(self,expr):
        try:
            hello(expr)
        except Test_case_error:
            if self.muffled:
                print('I can do it!')
            else:
                raise
# 打开异常处理
test_Exception = MuffledCalculator(True)
test_Exception.calc('1')

# 关闭异常处理
test_Exception = MuffledCalculator(False)
test_Exception.calc('1')

# 多个except处理子句
class MuffledCalculator:
    def __init__(self,muffled):
        self.muffled = muffled
    def calc(self,expr):
        try:
            hello(expr)
        except Test_case_error:
            if self.muffled:
                print('I can do it!')
            else:
                raise
        except NameError:
            print('The name ERROR!')

# 上面的简化版
class MuffledCalculator:
     def __init__(self,muffled):
         self.muffled = muffled
     def calc(self,expr):
         try:
             hello(expr)
         except Test_case_error:
             if self.muffled:
                  print('I can do it!')
             else:
                 raise
             except NameError:
                 print('The name ERROR!')

# 捕捉对象,期望发生异常时程序继续运行但异常信息同时也需要输出
filename = 'haha'
try:
    hello(filename)
except KeyError as e:
    print(e)

print('The programmer is still continue')

# 捕捉所有异常,可采用在except后不跟任何异常
filename = 'haha'
try:
    hello(filename)
except:
    print('Something wrong happen!')

# 加入else子句实现循环的处理问题
# 如下实例,只有在无异常时才会退出循环
while True:
    try:
        x = input('X:')
        y = input('Y:')
        value = x/y
        print ('x/y is' ,value)
    except:
        print('Invalid input,Try again!')
    else:
        break

# finally 子句,用来在可能的异常后进行清理,一下实例,不管是否有异常finally子句都会被执行
x = None
try:
    x = 1/0
finally:
    print('cleaning up!')
    del(x)
# 本例中如果不对x的赋值做清除, x将有于异常的存在一直无法赋值

# 让我们尝试下try except else finally兼而有之
try:
    1/0
except:
    print('Unknown variable!')
else:
    print('That went well!')
finally:
    print('Cleaning up!')

# 让异常与函数结合,让你的异常处理更简洁方便;
# 如果异常在函数内引发而不被处理,异常将传播到调用该函数的位置,若仍然未被处理将一直到达主程序
def faulty():
    raise Exception('something is wrong!')

def ignore_exception():
    faulty()

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

handle_exception()
ignore_exception()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值