简体   繁体   English

Java方法包含另一个抛出异常的方法

[英]Java method contains another method throws exception

Inside Method A, there is method B. Method B throws exception, but method A compiled even it does not catch exception or throws exception, could it be possible? 在方法A中,有方法B。方法B引发异常,但是方法A编译后即使没有捕获异常或引发异常,也可能吗?

Method B is something like as below: 方法B如下所示:

MethodB() throws SomeException{
   if(Some)
        doneSomething
        return
   else if(some)
        donesomethingElse
        return 
   throw SomeException  
}

If the SomeException extends RuntimeException . 如果SomeException扩展RuntimeException Then you don't need to catch it even if the signature looks like that. 然后即使签名看起来像你也不需要抓住它。

Also note that you can just remove the throws SomeException in that case. 另请注意,在这种情况下,您可以删除throws SomeException Read more here . 在这里阅读更多。

Yes, there are some unchecked exception, who might not be caught / rethrown. 是的,有一些未经检查的例外,可能不会被抓住/重新抛出。

Look at this tutorial - Unchecked Exceptions . 查看本教程 - 未经检查的异常

Even if SomeException is a checked exception, this can happen due to separate compilation. 即使SomeException是已检查的异常,也可能由于单独的编译而发生。

Suppose you write a class: 假设你写了一个类:

public class B {
  public static void foo() {
  }
}

Then a class that calls it: 然后是一个调用它的类:

public class A {
  public static void main(String[] args) {
    B.foo();
  }
}

Then say: 然后说:

javac A.java
java A

All is fine. 一切都很好。 Now change B: 现在换B:

public class B {
  public static void foo() throws java.io.IOException {
    throw new java.io.IOException();
  }
}

And this time just compile B before running: 这次只是在运行之前编译B:

javac B.java
java A

You get: 你得到:

Exception in thread "main" java.io.IOException
    at B.foo(B.java:4)
    at A.main(A.java:4)

In the real world this happens when individual .jar files are updated after they've been modified by maintainers who don't understand the problems caused by adding more throws clauses. 在现实世界中,当个别.jar文件被维护者修改后更新时会发生这种情况。维护人员不了解添加更多throws子句所导致的问题。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM