简体   繁体   English

在Java中抛出匿名异常

[英]Throw anonymous exceptions in Java

It is possible in Java to throw any Exception even if it is just declared on moment of throwing, example below: 在Java中有可能抛出任何异常,即使它只是在抛出的时刻声明,例如下面的例子:

import org.springframework.dao.DataAccessException;

 // DataAccessException - is abstract class

 } catch (DataAccessException dae) {
      throw new DataAccessException("Exception while executing SQL: \n" + sql
            +    "\nparams: " + paramsToString(params), dae) {
                          private static final long serialVersionUID = 1L;
      };
 } 

Please share your ideas how bad or good this approach. 请分享您的想法这种方法有多糟糕或不好。

the same question to extending RuntimeException (that is not abstract) and throw it right away. 同样的问题是扩展RuntimeException(不是抽象的)并立即抛出它。

Please share your ideas how bad or good this approach. 请分享您的想法这种方法有多糟糕或不好。

It should be legal ... according to my understanding of the Java language. 它应该是合法的...根据我对Java语言的理解。

I think it is pointless from a functional perspective. 从功能的角度来看,我认为这是毫无意义的。 The caller still has to catch the base exception that you created the anonymous subtype of. 调用者仍然必须捕获您创建匿名子类型的基本异常。 And it is not like the name of an anonymous subclass conveys any useful information ... 而且它不像匿名子类的名称传达任何有用的信息......

I think it is bad from the perspective of code readability and maintainability. 从代码可读性和可维护性的角度来看,我认为这很糟糕。 It is obscure for no good reason, and no useful effect that I can discern. 这是没有充分理由的模糊,也没有我能辨认出的有用效果。

And there is a risk that doing something weird like that it might break things .... such as your debuggers, source-code analysers or some other tool in your Java chain. 做一些奇怪的事情就像它可能会破坏一些东西......例如你的调试器,源代码分析器或Java链中的其他工具。


In summary, it is a bad idea with no redeeming features. 总之,没有兑换功能是一个坏主意。

Yes. 是。 Your example is perfectly okay. 你的例子完全没问题。 An Exception instance is just a class (that extends Exception) name plus information that will be needed when it's caught. Exception实例只是一个类(扩展了Exception)名称以及捕获时需要的信息。 Often the class name is all you need (for the catch statement). 通常,类名称就是您所需要的(对于catch语句)。 Normally a message and a stack trace are included. 通常包括消息和堆栈跟踪。 (Though they're both rather useless for caught exceptions.) But sometimes more info is needed. (虽然它们对于捕获的异常都是无用的。)但有时需要更多信息。 Extending a class is one good way to do that. 扩展课程是一种很好的方法。

If performance matters (which when working with SQL it might not) override fillInStackTrace . 如果性能很重要(使用SQL时可能不会)覆盖fillInStackTrace Filling in the stack trace is slow, and if you're planning to catch the exception, you don't need it. 填充堆栈跟踪很慢,如果您计划捕获异常,则不需要它。

Don't extend RunTimeException; 不要扩展RunTimeException; you won't be warned about methods that could throw it and you may forget to catch it. 你不会被告知可以抛出它的方法,你可能忘了抓住它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM