为什么? “总是将用户定义的异常声明为最终的”。 [英] Why? "Always declare user defined exceptions as final"

查看:88
本文介绍了为什么? “总是将用户定义的异常声明为最终的”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Java源代码分析器分析了正在处理的代码。警告之一是始终将用户定义的异常声明为最终的。还有许多其他警告并没有多大意义,但这使我有些困惑。

I analyzed the code I am working on using a Java source code analyzer. One of the warnings is "Always declare user defined exceptions as final". There are many other warnings that doesn't make much sense but this one made me a little bit confused.

我正在开发一个框架,但有一个根泛型异常(例如FrameworkGenericException),对于其他异常,我只是从根异常派生它们。因此,我对该框架有一个异常层次结构。我可能会扩展层次结构,但是我认为这个警告告诉我不要具有这样的层次结构,而要分别定义它们。那么我应该走哪条路,您的意见是什么?

I am working on a framework and I have one root generic exception (say FrameworkGenericException) and for other exceptions I am simply deriving them from the root exception. So I have a hierarchy of exceptions for the framework. I might extend the hierarchy but this warning I think tells me not to have such hierarchy but define them individually. So what which way should I go, what are your comments?

推荐答案

这可能是他们的标准做法:将类声明为final如果不应该继承它们,并且他们可能还认为您的所有异常都不会继承。

This is probably standard practice to them: declare classes as final if they are not supposed to be inherited from, and also they probably think that all of your exceptions won't be extended from.

但是,在您的情况下,我认为定义一个通用异常并从中扩展所有其他异常是一件好事。假设您有:

However, in your case I think that it is a good thing to make one generic exception and extend all others from it. Say, you have:

public void frameworkMethod() throws IllegalDataException, InvalidCommandException;

其中,这些例外是 FrameworkException 的子分类。

where these exceptions are sublasses of FrameworkException. Then you could handle exceptions a little bit easier.

try {
    frameworkMethod();
} catch (FrameworkException ex) {
    logger.log(Level.SEVERE, "An exception occured!", ex);

    if (ex instanceof IllegalDataException) {
        // Do something to recover
    } else if (ex instanceof InvalidCommandException) {
        //Inform the user
    } //And so on...
}

所以我想说,如果您做对了,程序的体系结构将更易于使用。

So I'd say, you're doing the right thing, the architecture of your program will be easier to work with.

这篇关于为什么? “总是将用户定义的异常声明为最终的”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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