Java异常处理概念。为什么编译器允许在throws部分中写入异常,即使它不能被抛出? [英] Java exception handling concept. why do compiler allow to write exceptions in throws section even if it can not be thrown?

查看:193
本文介绍了Java异常处理概念。为什么编译器允许在throws部分中写入异常,即使它不能被抛出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我调查java异常处理并面临以下行为。



考虑代码片段:



片段1

h2>

  public void g(){
try {

} catch(FileNotFoundException e){/ /任何检查的例外

}

}

它是编译错误消息

  FileNotFoundException的无法访问的catch块。这个异常从来没有从try语句体中抛出



Snippet2



  public void g()throws FileNotFoundException {
}


$因此,对于第一个代码片段的结果,编译器可以计算方法是否可能或不可能抛出异常。



/ p>

我可以得出结论,特别是。但是我不是为什么。



问题 - 为什么编译器允许在throws部分写入异常,即使它不能被抛出?



我想了解完整的概念。



PS 我明白这个行为对应于文档,但有关于在java中了解异常处理概念的问题。

解决方案

编译器允许这样做,因为<$ c $该方法的c> throws 子句是方法的签名的一部分,而不是其实现的一部分。有可能实施可能会在某些时候发生变化,同时保持签名相同。一个旧的实现可能已经抛出一个被检查的异常,但是新的可能没有。或者签名的设计者可能希望给实现者提供灵活性,以便在不一定需要的时候抛出被检查的异常。


I investigate java exception handling and faced with following behaviour. It is non obviously for me.

consider the code snippet:

Snippet 1

public void g(){
        try {

        } catch (FileNotFoundException e) {//any checked exception

        }

}

It is compile error with message

Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body

Snippet2

public void g() throws FileNotFoundException{
}

It is compiles fine.

Therefore, on the results of the first code snippet, compiler can calculate if method possible or impossible to throws exception.

And I can make conclusion that it was made especially. But I don't why.

Point of question - why compiler do allow to write exceptions in throws section even if it can not be thrown?

I want to understand full concept.

P.S. I understand that this behavior corresponds to the documentation but question about understanding of exception handling concept in java.

解决方案

The compiler allows this because the throws clause of the method is part of the signature of the method, rather than part of its implementation. It is possible that the implementation might change at some point, while keeping the signature the same. An old implementation might have thrown a checked exception, but the new one might not. Or the designer of the signature might have wanted to give the implementer the flexibility to throw a checked exception when that is not always necessary.

这篇关于Java异常处理概念。为什么编译器允许在throws部分中写入异常,即使它不能被抛出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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