我们什么时候应该创建我们自己的java异常类? [英] When should we create our own java exception classes?

查看:167
本文介绍了我们什么时候应该创建我们自己的java异常类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从良好的设计/实践的角度来看,我们何时应该创建和使用自定义java异常类,而不是已经在java中预定义的那些?



在某些应用程序中我看到几乎没有,甚至没有自定义异常类创建,他们努力总是使用本机java异常。另一方面,有一些应用程序可以定义所有的自定义异常。



最佳做法是什么?



谢谢!

解决方案

异常处理的最佳做法



尝试



以下代码有什么问题?

  public class DuplicateUsernameException extends Exception {} 

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



我们可以添加有用的方法到 DuplicateUsernameException ,例如:

  public class DuplicateUsernameException 
扩展异常{
public DuplicateUsernameException
(String username){....}
public String requestedUsername(){...}
public String [] availableNames(){。 ..}
}

新版本提供了两个有用的方法: requestedUsername(),它返回所请求的名称,并且 availableNames()返回一个类似于所请求的用户名的数组。客户端可以使用这些方法通知所请求的用户名不可用,并且其他用户名可用。但是如果你不要添加额外的信息,那么然后抛出一个标准异常:

  throw新异常(用户名已被占用); 


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?

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.

What is the best practice?

Thanks!

解决方案

From Best Practices for Exception Handling:

Try not to create new custom exceptions if they do not have useful information for client code.

What is wrong with following code?

public class DuplicateUsernameException extends 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.

We could add useful methods to DuplicateUsernameException, such as:

public class DuplicateUsernameException
    extends Exception {
    public DuplicateUsernameException 
        (String username){....}
    public String requestedUsername(){...}
    public String[] 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");

这篇关于我们什么时候应该创建我们自己的java异常类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆