什么时候应该创建我们自己的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 no, or even none 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 everything.

最佳做法是什么?

谢谢!

异常处理的最佳做法

尝试不创建新的自定义

以下代码有什么问题?

public class DuplicateUsernameException extends Exception {}

不向客户端代码提供任何有用的信息,而不是指示性异常名称。不要忘记Java异常类与其他类一样,您可以添加您认为客户端代码将调用的方法以获取更多信息。

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 Exception("Username already taken");