2020-2-8(57)

class EvenOnly(list):
    def append(self,integer):
        if not isinstance(integer,int):
            raise TypeError("Only integers can be added")
        if integer % 2:
            raise ValueError("Only even numbers can be added")
        #list.append(self,integer)    
        super().append(integer)

#=========================================================================================

def no_return():
    print("I am about to raise an exception")
    raise Exception("This is always raised")
    print("This line will never execute")
    return "I won't be returned"

def call_exceptor():
    print("call_exceptor starts here...")
    no_return()
    print("an exception was raised...")
    print("...so these lines don't run")

try:
    call_exceptor()
except:
    print("I caught an exception")
print("execute after the exception")    

#=============================================================

def funny_division(num):
    try:
        if num == 13:
            raise ValueError("13 is an unlucky number!")
        return 100 / num
    except ZeroDivisionError:
        return "you can't divide by zero!"
    except TypeError:
        return "you can't divide by string!"
    except ValueError:
        print("999")
        
        
for num in [50,0,13,"1"]:
    print(funny_division(num))

#==============================================================================================

try:
    raise ValueError("This is an argument")
except ValueError as e:
    print("The exception arguments were",e.args[0])

#================================================================================

import random
some_exceptions = [ValueError,TypeError,IndexError,None]

try:
    choice = random.choice(some_exceptions)
    print("抛出%s异常" %choice)
    if choice:
        raise choice("An error")
except ValueError:
    print("Caught a ValueError")
except TypeError:
    print("Caught a TypeError")
except Exception as e:
    print("**Caught a %s" %e.__class__.__name__)

else:
    print("This code called if there is no exception")
finally:
    print("This cleanup code is always called")
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值