2

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);
BertNase
  • 2,374
  • 20
  • 24
NDeveloper
  • 1,837
  • 4
  • 20
  • 34
  • As Bert says, they're not 'checked exceptions', so try/catching is optional. The "throws" statement is only given as a 'hint'. Catch it if you like – laher May 26 '11 at 05:03
  • There is a very recently question here with lots of good information in its answers about the difference between checked and unchecked exceptions: http://stackoverflow.com/questions/6115896/java-checked-vs-unchecked-exception-explaination – Aleadam May 26 '11 at 05:11

2 Answers2

8

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

BertNase
  • 2,374
  • 20
  • 24
0

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.

Sky Kelsey
  • 19,192
  • 5
  • 36
  • 77