简体   繁体   中英

call method with checked exception

As I know if method throws an exception Java compiler forces the caller of that method to catch that exception.

I see that parseInt throws NumberFormatException :

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s,10);

So why I can call it wthout catching the exception:

String str = "5";
int n = Integer.parseInt(str);

Because NumberFormatException extends RuntimeException - Runtime Exceptions are considered to be 'unchecked', See the Javadoc of RuntimeException :

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.

A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.

Here is an article from the Java tutorial explaining how this feature is meant and why it exists

The important distinction is that any Exception that extends from Runtime exception does not need to be caught, while any other Exception does. Exceptions that extend RuntimeException can be thrown at any time, such as NullPointerException or ConcurrentModificationException, and so they can't expect you to try to catch them all.

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