简体   繁体   中英

Why does java allow a method which always throws an exception to declare the return type as that exception?

Why does java allow a method which always throws an exception to declare the return type as that exception? Both the following methods are valid:-

public RuntimeException alwaysFails() {
    throw new RuntimeException("failed");
}

public void alwaysFailsButVoid() {
    throw new RuntimeException("failed");
}

What's the benefit of allowing this?

You can declare any type to be the return type of the method. Since the method never returns normally, this is perfectly true (but misleading).

Note that the Java compiler cannot determine for certain when your methods might return normally, in general (due to the Halting Problem being unsolvable).

The benefit of allowing this is to allow you to subclass a class or inherit an interface which has already pre-specified the return type for that method. It's essential for Object-Oriented Programming.

回归和投掷不是一回事,他们是独立的。

I'm not seeing the issue. There is no compile time cross check between return types and possible exceptions. There is no relationship. The compiler only checks to see what checked exceptions are possible and what exceptions are declared with regards to exceptions (obviously, the compiler does a whole lot more beyond this).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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