类 用于管理异常
Classes used to manage exception
有一个 class 用于捕获异常的短方法好吗?
class ContractUtils{
public static String getCode(Contract contract) throws MyException{
try{
return contract.getInfo().getCode(); //throws ContractException and LogicException
}catch(Exception e){
throw new MyException("error during code reading:"+e.getMessage, e);
}
}
//other methods like above...
}
最好在代码中分别捕获和处理异常。不建议分配常见的自定义异常。
请参阅此 link 以了解管理异常的最佳做法:
如果自定义异常为调用代码提供了额外的上下文或价值,那么创建它们是有用的,我们鼓励您创建它们。
您使用静态方法的方法是完全可以接受的。这是一个很好的 SO answer 定义短静态方法的用例。
您的实用程序 class ContractUtil
引入了 间接级别 只是为了将原始异常转换为另一个异常:
而不是直接调用:
return contract.getInfo().getCode()
你现在写的比较人工
return ContractUtils.getCode(contract);
但在某些情况下,此解决方案可能合理,例如:
You are
not allowed to throw ContractException or LogicException, and you are calling this method a lot
of times.
但是如果你能改变它的签名,最好重新设计原来的方法只抛出 MyException
.
为了可读性,将应用程序逻辑与错误处理分开可能很有用。
但不在实用程序 class 中,因为您可能会忘记使用它,直接完成它的任务,但仍然期待自定义异常。如果使用得足够频繁(并使 Contract.getInfo() 私有),我会将此逻辑放在 Contact class 中。另一个缺点是,它可能导致实用程序 classes 对其他 classes 的实现细节过于了解(LoD - https://en.wikipedia.org/wiki/Law_of_Demeter),可能会破坏封装并使它们更难维护,因为更高的依赖性。
而且,您可能想要捕获特定的异常。
有一个 class 用于捕获异常的短方法好吗?
class ContractUtils{
public static String getCode(Contract contract) throws MyException{
try{
return contract.getInfo().getCode(); //throws ContractException and LogicException
}catch(Exception e){
throw new MyException("error during code reading:"+e.getMessage, e);
}
}
//other methods like above...
}
最好在代码中分别捕获和处理异常。不建议分配常见的自定义异常。
请参阅此 link 以了解管理异常的最佳做法:
如果自定义异常为调用代码提供了额外的上下文或价值,那么创建它们是有用的,我们鼓励您创建它们。
您使用静态方法的方法是完全可以接受的。这是一个很好的 SO answer 定义短静态方法的用例。
您的实用程序 class ContractUtil
引入了 间接级别 只是为了将原始异常转换为另一个异常:
而不是直接调用:
return contract.getInfo().getCode()
你现在写的比较人工
return ContractUtils.getCode(contract);
但在某些情况下,此解决方案可能合理,例如:
You are not allowed to throw ContractException or LogicException, and you are calling this method a lot of times.
但是如果你能改变它的签名,最好重新设计原来的方法只抛出 MyException
.
为了可读性,将应用程序逻辑与错误处理分开可能很有用。
但不在实用程序 class 中,因为您可能会忘记使用它,直接完成它的任务,但仍然期待自定义异常。如果使用得足够频繁(并使 Contract.getInfo() 私有),我会将此逻辑放在 Contact class 中。另一个缺点是,它可能导致实用程序 classes 对其他 classes 的实现细节过于了解(LoD - https://en.wikipedia.org/wiki/Law_of_Demeter),可能会破坏封装并使它们更难维护,因为更高的依赖性。
而且,您可能想要捕获特定的异常。