在Java中引发匿名异常 [英] Throw anonymous exceptions in Java

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

问题描述

在Java中,即使在抛出时声明了异常,也可能抛出任何异常,如下所示:

 导入org.springframework.dao.DataAccessException; 

// DataAccessException-是抽象类

} catch(DataAccessException dae){
throw new DataAccessException(执行SQL时出现异常:\n + sql
+ \nparams: + paramsToString(params),dae){
private static final long serialVersionUID = 1L;
};
}

请分享您的想法这种方法的优劣。



与扩展RuntimeException(不是抽象的)并立即抛出该问题相同。

解决方案


请分享您的想法这种方法的优劣。


应该合法。根据我对Java语言的理解。



从功能的角度来看,我认为这毫无意义。调用方仍然必须捕获您为其创建匿名子类型的基本异常。而且这并不像匿名子类的名称传达任何有用的信息...



从代码的可读性和可维护性的角度来看,我认为这是不好的。



毫无理由,这是晦涩的。



还有一种奇怪的事情,可能会破坏事情...






总之,它是Java链中的调试器,源代码分析器或其他工具。没有兑换功能的坏主意。


It is possible in Java to throw any Exception even if it is just declared on moment of throwing, example below:

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.

解决方案

Please share your ideas how bad or good this approach.

It should be legal ... according to my understanding of the Java language.

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.


In summary, it is a bad idea with no redeeming features.

这篇关于在Java中引发匿名异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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