异常处理模式 [英] Exception handling pattern

查看:90
本文介绍了异常处理模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个常见的模式,我看到与异常关联的错误代码存储为静态final int。当异常被创建以被抛出时,它被构造为这些代码之一以及错误消息。
这将导致该方法将捕获它必须查看代码,然后决定一个操作过程。

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 ?

推荐答案

这是一个很好的问题。我相信绝对有一个中间地位。

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.

为了以编程方式处理错误,我个人不推荐错误代码,我会为每个类别的错误推荐一个新的类,但绝对不是每一个错误。 Java做了一个体面的工作让我们开始了异常,如IOException,IllegalArgumentException,UnsupportedOperationException等。我经常在我的代码中抛出并捕获这些。

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.

如果你有您的代码应该以编程方式响应的新类别的异常,那么您应该肯定为其创建一个新类,扩展相应的父类。例如UserRegistrationException或ProductException。

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.

这篇关于异常处理模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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