tags:

views:

254

answers:

4

I've noticed with Integer.parseInt() that you don't have to surround it with a try catch or declare that the method might throw an exception, despite the fact that it "throws" a NumberFormatException.

Why don't I have to explicitly catch the NumberFormatException or state that my method throws it?

+6  A: 

NumberFormatException extends RuntimeException, you don't have to explicitly handle anything that inherits from RuntimeException.

Other RuntimeExceptions are things like NullPointerException and IndexOutOfBoundsException. These are things the programmer can avoid and having to try/catch these types of exceptions would create some pretty cluttered code.

bobwienholt
+13  A: 

Because that is a "runtime" exception.

RuntimeExceptions are used to identify programming problems ( that a good programmer could avoid ) while

Checked exceptions are to identify environment problems ( that could not be avoided no matter how good do you program , a server is down for instance )

You could read more about them here

There are actually three kinds of exceptions, only one of them should be handled ( most of the times )

OscarRyz
+6  A: 
         Throwable
         /      \
      Error    Exception
                /     \
           *checked*  RuntimeException
                            \
                         *unchecked*

See Thinking in Java for a good explanation of Checked vs. Unchecked exceptions.

Some consider the idea of checked exceptions a failed experiment. For example, both Spring and Hibernate use unchecked exceptions, and often wrap checked exceptions in unchecked versions.

toolkit
+1  A: 

Just a long comment on toolkit's answer.

The reason Checked exceptions are a problem is that they eventually lead to code like this:

try {
    Something that throws an exception
} catch (Exception e) {}

This is worst case. First of all, they are not logging that they are catching the exception. This happens a lot, and is almost FORCED by very stupid checked exceptions like the one on Thread.sleep(), it throws InterruptedException that MUST be caught, but 99% of the time you couldn't care less if you got one or not.

In the case above, it's compounded by the fact that people tend to just catch "Exception" if there are more than one thrown. That means that even if a critical unchecked exception is thrown, it will be caught and ignored making it virtually impossible to find the problem.

More than once I've been on teams that had to spend about a man-month trying to track down bugs hidden in this way.

It's a good concept that becomes horrible when you add in the fact that humans are the ones who must implement it responsibly.

Bill K