Reputation: 1847
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);
Upvotes: 2
Views: 448
Reputation: 19290
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.
Upvotes: 0
Reputation: 2414
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
Upvotes: 8