不能使用try / catch块来处理java未检查的异常? [英] can't java unchecked exceptions be handled using try/catch block?

查看:364
本文介绍了不能使用try / catch块来处理java未检查的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在教程中,我发现无法通过代码处理未选中的异常,即我们无法使用 try / catch 块和示例是例如 ArrayIndexOutOfBoundsException,NullPointerException。但是这些异常可以使用try / catch块来处理。我想我不清楚这个概念!

In a tutorial I found that Unchecked Exception can't be handled by your code i.e. we can't use try/catch block and the examples are exceptions like ArrayIndexOutOfBoundsException, NullPointerException. But these exceptions can be handled using try/catch block. I think i am not clear about the concept !!

另外我认为throw关键字只能用于 try / catch block.can throw关键字与 UncheckedException

Also i think throw keyword can be used only with try/catch block.can throw Keyword be used with UncheckedException?

推荐答案

检查和未检查异常之间的唯一区别是检查 要使用 throws 在方法签名中被捕获或声明,而未选中的则是可选的。

The only difference between checked and unchecked exceptions is that checked ones have to be either caught or declared in the method signature using throws, whereas with unchecked ones this is optional.


未选中的异常不能由您的代码处理,即我们无法使用try / catch块

Unchecked Exception can't be handled by your code i.e. we can't use try/catch block

当然我们可以 - 但是我们不必。

Sure we can - but we don't have to.


我也认为可以使用throw关键字只能使用try / catch block.can throw关键字与Unchecked Exception一起使用

Also i think throw keyword can be used only with try/catch block.can throw Keyword be used with Unchecked Exception?

请注意,有两个关键字:

Note that there are two keywords:


  • throw 显式抛出您创建的异常对象。 抛出新的NullPointerException(); 非常好,尽管明确地创建了特定的异常是不常见的,大多数人会认为它是坏的风格。

  • throws 声明方法可能会抛出该异常。使用未检查的异常,这是可选的,但可以用于记录事实(再次,通常不会声明 throws NullPointerException ,因为这是一个给定的)。 >
  • throw explicitly throws an exception object you created. throw new NullPointerException(); works perfectly fine, though explicitly creating that particular exception is uncommon and most would consider it bad style.
  • throws declares that a method may throw that exception. With unchecked exceptions this is optional, but can be useful to document the fact (again, one would normally not declared throws NullPointerException because that is pretty much a given).

这篇关于不能使用try / catch块来处理java未检查的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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