Korg
Korg

Reputation: 93

Error - Unhandled exception type Exception?

I made a method which throws an Exception(). It causes an error - Unhandled exception type Exception

public void temp(){
  throw new Exception();
}

However, if I replace Exception with any other Exception such as NullPointerException, i don't get any error. Why is this happening ?

Upvotes: 2

Views: 9477

Answers (2)

Alex Cohn
Alex Cohn

Reputation: 57173

I got stuck with a strange situation with this error. Namely, my Eclipse built the code without warnings, but for two of my colleagues compiler was giving this error. It took us a while to figure out, mainly because there is an easy remedy of using RuntimeException. But finally, the trick was that their Eclipse was set up for Java 1.6, while mine was tuned for 1.7.

Upvotes: 1

Blake
Blake

Reputation: 591

That's the difference between a "checked" exception and an "unchecked" exception. Anything that extends RuntimeException, including NullPointerException, are "unchecked" which means they don't need to be explicitly handled via a try/catch or by declaring that the method throw them.

Checked exceptions are those that do not extend RuntimeException and must be handled either by try/catch or by declaring your method throw it. So your code fails to compile because you are not handling it either way.

Upvotes: 8

Related Questions