简体   繁体   English

为什么一个方法可以被声明为抛出许多异常,即使它们都没有被抛出?

[英]Why can a method be declared to throw many exceptions even if none of them are thrown?

I was merging my source code with that of a colleague and I saw he had added an exception to be thrown in the declaration of a method; 我正在将我的源代码与同事的源代码合并,我看到他添加了一个异常,要在方法的声明中抛出; however, I knew, that exception would never be really thrown from that method. 但是,我知道,该异常永远不会从该方法中抛出。

I wonder why the compiler did not warn me about a "non-thrown exception declared" (or something like that). 我想知道为什么编译器没有警告我“声明的非抛出异常”(或类似的东西)。 I realize that you can declare a method throwing N exceptions, even if none of those exceptions is thrown by the code in the method. 我意识到你可以声明一个抛出N个异常的方法,即使方法中的代码没有抛出这些异常。

Why is that? 这是为什么?

public void foo() throws IOException, IntrospectionException,  BadStringOperationException, ... {
    //do nothing
}
  1. Subclasses that override the method may throw the exception, even if its superclass doesn't. 重写该方法的子类可能会抛出异常,即使它的超类没有。
  2. You can later change the method to throw one of the listed exceptions while maintaining backwards compatibility. 您可以稍后更改方法以抛出其中一个列出的异常,同时保持向后兼容性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么只能在方法签名中将某些异常声明为抛出 - Why must only certain Exceptions be declared as thrown in method signature 为什么不能在方法级别抛出Java流中的检查异常? - Why can't checked exceptions in a java stream be thrown at method level? 如果一个方法可以抛出多个异常,如何声明? - If a method can throw multiple exceptions, how to declare it? 为什么重写方法不能抛出比重写方法更广泛的异常? - Why can't overriding methods throw exceptions broader than the overridden method? 为什么会话 bean 方法在抛出 RuntimeException 时抛出 EjbTransactionRolledbackException - Why session bean method throw EjbTransactionRolledbackException when RuntimeException was thrown 我怎么知道方法可以抛出什么异常? - How can I know what exceptions can be thrown from a method? 为什么在使用方法计数时从模拟中抛出的异常消失了? - Why are exceptions thrown from mocks gone when using method count? 我可以在一种测试方法中测试多个抛出的异常吗? - Can I test for multiple thrown exceptions in one test method? JdbcTemplate.execute()方法可以抛出的所有异常 - All the exceptions that can be thrown by JdbcTemplate.execute() method 如何查看给定方法中引发的运行时异常? - How can I see the runtime exceptions thrown within a given method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM