我们什么时候应该创建自己的 Java 异常类?
从好的设计/实践的角度来看,我们什么时候应该创建和使用自定义 Java 异常类而不是 Java 中已经预定义的类?
From a good design/practice point of view, when should we create and use custom Java exception classes instead of the ones already predefined in Java?
在一些应用程序中,我看到几乎创建了自定义异常类,它们努力始终使用本机 Java 异常.另一方面,有些应用程序为(几乎)所有内容定义了自定义异常.
In some applications I see almost custom exception classes created, they make an effort to always use native Java exceptions. On the other hand, there are some applications that define custom exceptions for (almost) everything.
来自 异常处理的最佳实践:
如果没有关于客户端代码的有用信息,尽量不要创建新的自定义异常.
下面的代码有什么问题?
What is wrong with the following code?
public class DuplicateUsernameException extends Exception {}
除了指示性异常名称之外,它没有向客户端代码提供任何有用的信息.不要忘记 Java Exception 类与其他类一样,您可以在其中添加您认为客户端代码将调用以获取更多信息的方法.
It is not giving any useful information to the client code, other than an indicative exception name. Do not forget that Java Exception classes are like other classes, wherein you can add methods that you think the client code will invoke to get more information.
我们可以在DuplicateUsernameException
中添加有用的方法,例如:
We could add useful methods to DuplicateUsernameException
, such as:
public class DuplicateUsernameException
extends Exception {
public DuplicateUsernameException
(String username){....}
public String requestedUsername(){...}
public String[] availableNames(){...}
}
新版本提供了两个有用的方法:requestedUsername()
,它返回请求的名称,以及 availableNames()
,它返回一个可用用户名的数组,类似于一个要求.客户端可以使用这些方法来通知请求的用户名不可用而其他用户名可用.但是如果你不打算添加额外的信息,那就抛出一个标准异常:
The new version provides two useful methods: requestedUsername()
, which returns the requested name, and availableNames()
, which returns an array of available usernames similar to the one requested. The client could use these methods to inform that the requested username is not available and that other usernames are available. But if you are not going to add extra information, then just throw a standard exception:
throw new IllegalArgumentException("Username already taken");