自定义在myexception模块中的异常类MyException
class MyException(Exception):
def init(self,val1,val2):
self.val1=val1
self.val2=val2
main.py
import myexception
class Test(object):
def init(self,switch):
self.switch=switch #开关
def calc(self,a,b):
try:
#return a/b
if b<3:
raise myexception.MyException(a,b)
except NameError:
print("NameError 发生了 ...")
except myexception.MyException as me:
print("MyException 发生了 ...")
except Exception as e:
if self.switch:
print("异常捕获开启,异常信息如下:")
print(e)
else:
print("异常捕获关闭,抛出异常 ...")
raise
else:
print("没有异常才执行的语句 ...")
print("除非有异常且异常交由python处理,否则都会打印的语句 ...")
test=Test(1)
test=Test(0)
test.calc(5,0)