java 异常处理模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4589750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:06:25  来源:igfitidea点击:

Exception handling pattern

javaexceptionenumsdesign-patterns

提问by treefrog

It is a common pattern I see where the error codes associated with an exception are stored as Static final ints. when the exception is created to be thrown, it is constructed with one of these codes along with an error message. This results in the method that is going to catch it having to look at the code and then decide on a course of action.

这是我看到的一种常见模式,其中与异常相关的错误代码存储为静态最终整数。当创建要抛出的异常时,它由这些代码之一和错误消息构成。这导致要捕获它的方法必须查看代码,然后决定采取行动。

The alternative seems to be- declare a class for EVERY exception error case (although related exceptions would derieve from a common base class )

替代方案似乎是 - 为每个异常错误情况声明一个类(尽管相关的异常会派生自一个公共基类)

Is there a middle ground ? what is the recommended method ?

有中间立场吗?推荐的方法是什么?

采纳答案by satur9nine

This is a good question. I believe there is definitely a middle ground.

这是一个很好的问题。我相信肯定有一个中间立场。

Error codes are essential in my opinion for displaying errors to QA, and for customers to report to customer support and back to developers.

在我看来,错误代码对于向 QA 显示错误以及让客户报告给客户支持并返回给开发人员至关重要。

For programmatically handling errors I personally don't recommend error codes, I'd recommend a new Class for each category of errors, but definitely not for every single error. Java did a decent job getting us started with Exceptions like IOException, IllegalArgumentException, UnsupportedOperationException, etc. I frequently throw and catch these when appropriate in my code.

对于以编程方式处理错误,我个人不推荐错误代码,我会为每个错误类别推荐一个新类,但绝对不是每个错误。Java 做得不错,让我们开始处理 IOException、IllegalArgumentException、UnsupportedOperationException 等异常。我经常在我的代码中适当地抛出和捕获这些异常。

If you have a new category of exceptions that your code should respond to programmatically then you should definitely create a new class for it, extending the appropriate parent class. For example UserRegistrationException or ProductException.

如果您的代码应该以编程方式响应一类新的异常,那么您绝对应该为它创建一个新类,扩展适当的父类。例如 UserRegistrationException 或 ProductException。

回答by weltraumpirat

To answer your specific question: Your decision should be based on how and why your exceptions will be processed. Do you want to make your program as foolproof as possible and conveniently react to every possible error scenario individually? Then you should indeed create an Exception class for every possible error cause you can identify. Otherwise, it is best to decide for each case individually.

回答您的具体问题:您的决定应基于处理例外情况的方式和原因。您想让您的程序尽可能万无一失,并方便地单独对每种可能的错误情况做出反应吗?那么您确实应该为您可以识别的每个可能的错误原因创建一个 Exception 类。否则,最好为每个案例单独决定。

There are a number of very common errors that jeopardize the stability of your entire program (such as ClassNotFoundException or NoSuchMethodException) - these should definitely be handled specifically. There are other errors that are closely related to one another, resulting in similar problems - these can very well be grouped or organized hierarchically (IOException stands for all kinds of errors related to in- or output, NetworkIOException stands only for in- and output errors related to network access, etc.).

有许多非常常见的错误会危及整个程序的稳定性(例如 ClassNotFoundException 或 NoSuchMethodException)——这些绝对应该被专门处理。还有其他错误彼此密切相关,导致类似的问题——这些错误可以很好地按层次分组或组织(IOException 代表与输入或输出相关的所有类型的错误,NetworkIOException 仅代表输入和输出错误与网络访问等相关)。

Far more important than the exception's name and class hierarchy, in my opinion, is what you do with it: Where do you place your try/catch blocks? Which log entries should be written for which log file? Who should be notified? Which error messages should be presented only to admins/developers? Which errors should be communicated to the end user?

在我看来,比异常的名称和类层次结构更重要的是你用它做什么:你在哪里放置你的 try/catch 块?应该为哪个日志文件写入哪些日志条目?应该通知谁?哪些错误消息应该只显示给管理员/开发人员?哪些错误应该传达给最终用户?

There are many patterns for handling exceptions, answering all sorts of questions like these. A quite extensive collection of common and useful patterns can be found here.

有许多处理异常的模式,可以回答诸如此类的各种问题。可以在此处找到大量常见且有用的模式。

回答by DVK

If you can generalize the behavior across different error cases, especially if such behavior can be classified into "classes" of behavior (no pun intended), having an exception class hierarchy makes sense.

如果您可以在不同的错误情况下概括行为,尤其是如果此类行为可以归类为行为的“类”(无意双关语),则具有异常类层次结构是有意义的。

If you must catch EVERY (or almost) every exception anyway, and the handling of most of them is nearly identical (e.g. print error and quit), having 1 class with exception number in it makes sense as it's a simpler design.

如果无论如何您必须捕获每个(或几乎)每个异常,并且对它们中的大多数的处理几乎相同(例如打印错误和退出),那么拥有 1 个带有异常编号的类是有意义的,因为它是一个更简单的设计。

回答by leonbloy

The "middle ground", as I see it, is to use the internal "error codes" (common pattern, but not VERY common, IMO) as additional information for reporting/informational purposes; but not for deciding who catches the exception (this is determined by the exception class).

在我看来,“中间地带”是使用内部“错误代码”(常见模式,但不是很常见,IMO)作为报告/信息目的的附加信息;但不是决定谁捕获异常(这是由异常类决定的)。