为什么spring只处理未经检查的异常 [英] why spring handles only unchecked exceptions

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

问题描述

我想知道为什么spring只处理未经检查的异常.....任何人都可以解释这背后的原因。

I want to know why spring handles only unchecked exceptions..... can any one explain what is the reason behind this .

Spring正在使用任何设计模式这将避免检查异常?

Spring is using any design patterns which will avoid checked exceptions ?

推荐答案


Spring正在使用任何设计模式,以避免检查
异常?

Spring is using any design patterns which will avoid checked exceptions ?

不是设计模式,而是异常处理的最佳实践

考虑下面的代码:

public void consumeAndForgetAllExceptions(){
    try {
        ...some code that throws exceptions
    } catch (Exception ex){
        ex.printStacktrace();
    }
}

上面的代码出了什么问题?

What is wrong with the code above?

一旦抛出异常,正常程序执行就会暂停,控制权将转移到catch块。 catch块捕获异常并且只是抑制它。在catch块之后继续执行程序,就像没有发生任何事情一样。

Once an exception is thrown, normal program execution is suspended and control is transferred to the catch block. The catch block catches the exception and just suppresses it. Execution of the program continues after the catch block, as if nothing had happened.

以下内容如何?

public void someMethod() throws Exception{
}

这个方法是空白的;它没有任何代码。 如何使用空白方法抛出异常? Java并不会阻止您这样做。

This method is a blank one; it does not have any code in it. How can a blank method throw exceptions? Java does not stop you from doing this.


我想知道为什么spring只处理未经检查的异常?

I want to know why spring handles only unchecked exceptions?

我个人更喜欢在throws原因中声明的未经检查的异常。当我对它们不感兴趣时​​,我讨厌必须捕获异常。我同意规范需要更多的异常类型,但我不同意它们应该被检查。大多数框架都依赖于未经检查的异常,而不仅仅是Spring框架。

Personally I prefer unchecked exceptions declared in the throws cause. I hate having to catch exceptions when I'm not interested in them. I agree the spec needs to a few more exception types, but I disagree that they should be checked. Most frameworks rely on unchecked exceptions, not only Spring framework.


  • 如果客户端可以采取一些备用操作从异常中恢复,请将其设为已检查的异常

  • 如果客户端无法执行任何有用的操作,然后取消选中异常。有用的,我的意思是采取措施从异常中恢复,而不仅仅是记录异常。

  • If the client can take some alternate action to recover from the exception, make it a checked exception.
  • If the client cannot do anything useful, then make the exception unchecked. By useful, I mean taking steps to recover from the exception and not just logging the exception.

Java API有许多未经检查的异常,
,例如
NullPointerException IllegalArgumentException ,以及 IllegalStateException 。我更喜欢使用Java中提供的标准异常,而不是创建自己的异常。它们使我的代码易于理解,并避免增加代码的内存占用。

The Java API has many unchecked exceptions, such as NullPointerException, IllegalArgumentException, and IllegalStateException. I prefer working with standard exceptions provided in Java rather than creating my own. They make my code easy to understand and avoid increasing the memory footprint of code.

另见:

  • Unchecked Exceptions
  • Best practices in exception handling

这篇关于为什么spring只处理未经检查的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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