您是否针对特定问题或一般例外编写例外情况? [英] Do you write exceptions for specific issues or general exceptions?

查看:132
本文介绍了您是否针对特定问题或一般例外编写例外情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,给一个实用程序的用户ID,然后发送电子邮件给该用户。

I have some code that gives a user id to a utility that then send email to that user.

emailUtil.sendEmail(userId, "foo");

public void sendEmail(String userId, String message) throws MailException {
    /* ... logic that could throw a MailException */
}

MailException 可能会被抛出,原因有很多,电子邮件地址有问题,邮件模板的问题等。

MailException could be thrown for a number of reasons, problems with the email address, problems with the mail template etc.

我的问题是这样:为每个异常创建一个新的异常类型,然后单独处理创建一个MailException,然后在异常中存储某些东西(一些计算机可读的,不是描述文本),这样我们可以根据实际发生的情况来做不同的事情。

My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened.

编辑:作为一个澄清,异常不是针对日志而不是,这与代码对它们的反应如何相关。要继续使用邮件示例,假设我们发送邮件时可能会因为没有电子邮件地址而失败,否则可能是因为您没有有效的电子邮件地址,或它可能会失败..等。

As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a valid email address, or it could fail.. etc.

我的代码想要对每个这些问题做出不同的反应(主要是通过更改返回给客户端的消息,但实际的逻辑也是)

My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well).

最好对每个这些问题执行异常实现,或者一个具有内部内容的伞状异常(一个枚举说),让代码区分出什么样的问题。

Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.

推荐答案

我通常从一般的异常开始,根据需要进行子类化。我总是可以捕获一般的异常(和它所有的子类异常),如果需要,还要具体。

I usually start with a general exception and subclass it as needed. I always can catch the general exception (and with it all subclassed exceptions) if needed, but also the specific.

Java-API的一个例子是IOException,子类如FileNotFoundException或EOFException(以及更多)。

An example from the Java-API is IOException, that has subclasses like FileNotFoundException or EOFException (and much more).

这样你就可以获得两者的优点,你没有throw-clause如:

This way you get the advantages of both, you don't have throw-clauses like:

throws SpecificException1, SpecificException2, SpecificException3 ...

一般

throws GeneralException

就够了。但是,如果您想对特殊情况有特殊反应,您可以随时掌握特定的例外情况。

is enough. But if you want to have a special reaction to special circumstances you can always catch the specific exception.

这篇关于您是否针对特定问题或一般例外编写例外情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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