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:
hello(filename)
except Test_case_error:
print(
'hello')
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')
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')
filename =
'haha'
try:
hello(filename)
except:
print(
'Something wrong happen!')
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
x =
None
try:
x =
1/
0
finally:
print(
'cleaning up!')
del(x)
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()