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")