本文介绍了不能使用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块一起使用.throw关键字可以与UncheckedException一起使用吗?

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

推荐答案

已检查和未检查的异常之间的唯一区别是,已检查的异常必须被捕获或在使用,而对于未选中的选项,这是可选的.

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.

当然可以-但我们不必这样做.

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

请注意,有两个 关键字:

Note that there are two keywords:

  • throw显式抛出您创建的异常对象. throw new 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未经检查的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 11:14