# -*- encoding: utf-8 -*-
import os
'''
第51条: 为自编的模块定义根异常,以便将调用者与API相隔离
1 根异常
应用:可以在模块中提供一种根异常后,然后令该该模块所抛出的其他异常,
都继承自这个根异常。
作用:
1) 捕获根异常,直到别人调用代码是否正确
2) 帮助开发者寻找API中的bug
3) 便于API的后续演化,提供更为具体的异常
关键:
参考:
Effectiv Python 编写高质量Python代码的59个有效方法
'''
class Error(Exception):
"""It is used to as base exception class."""
class InvalidDensityError(Error):
"""Density Error """
def getWeight(volume, density):
if density <= 0:
raise ValueError('Density must be positive')
result = volume * density
return result
def validGetWeight():
try:
result = getWeight(1, -1)
return result
except InvalidDensityError as ex:
info = "unexpected exception: {exp}, message: {mess}".format(
exp=ex.__class.__name__,
mess=ex
)
print info
def process():
validGetWeight()
if __name__ == "__main__":
process()