[英]Is reclassing exceptions good practice?
Sometimes I reclass an exception like this: 有时候我会重新排序这样的异常:
try{
methodA(param1);
}catch(ExceptionType1 ex){
throw new ExceptionType2(ex);
}
An example of when I do this is when methodA's params should be safe and will not throw exceptions, so the ExceptionType1 is really indicative of a different problem (something like ExceptionType2). 我这样做的一个例子是methodA的params应该是安全的并且不会抛出异常,所以ExceptionType1实际上表示一个不同的问题(类似于ExceptionType2)。
This is not reclassing from checked exception to unchecked. 这不是从已检查的异常重新分类到未选中。
There's nothing wrong; 没有错; in fact it's a commonly used pattern.
事实上,这是一种常用的模式。
Rethrowing an exception wrapped in another exception is often used when the method contract throws a domain specific exception, but there's an implementation specific exception you must deal with, for example an SQLException. 当方法契约抛出特定于域的异常时,通常会使用包含在另一个异常中的异常,但是必须处理一个特定于实现的异常,例如SQLException。
public Customer getCustomer(int id) throws CustomerDataUnavailableException {
try {
// access SQL database
return customer;
} catch ( SQLException e) {
throw new CustomerDataUnavailableException(e);
}
}
The choice to store customer data in an SQL database is an implementation choice, which you don't want to leak out through the API (by throwing SQLException). 将客户数据存储在SQL数据库中的选择是一种实现选择,您不希望通过API泄漏(通过抛出SQLException)。
It also makes changing the implementation easy, for example using a flat file system on a mobile device, or using a NoSql db - the change can be made to the method without changing any other code, because the API contract is implementation independent. 它还使得实现变得容易,例如在移动设备上使用平面文件系统,或使用NoSql数据库 - 可以在不更改任何其他代码的情况下对方法进行更改,因为API协议是独立于实现的。
Finally, it makes testing and mocking easier - you don't have to throw exotic exceptions, the classes of which may not even be accessible to your testing code. 最后,它使测试和模拟变得更容易 - 您不必抛出异国情况的异常,其中的类可能甚至无法被您的测试代码访问。
It is OK - according to this URL, this is defined as a "chained exception" and it is legal: 没关系 - 根据此URL,这被定义为“链式异常”并且是合法的:
http://docs.oracle.com/javase/tutorial/essential/exceptions/chained.html http://docs.oracle.com/javase/tutorial/essential/exceptions/chained.html
The following example shows how to use a chained exception. 以下示例显示如何使用链式异常。
try {
} catch (IOException e) {
throw new SampleException("Other IOException", e);
}
I would document the different types of exceptions using the @throws
tag for JAVADOC. 我将使用JAVADOC的
@throws
标记记录不同类型的异常。 It is legal to include multiple @throws
tags for one method; 为一个方法包含多个
@throws
标记是合法的; see this URL: 看到这个网址:
Can I use multiple @throws tags for the same exception in Javadoc? 我可以在Javadoc中为同一个异常使用多个@throws标记吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.