10

Why is the two exception types in Java named "checked" and "unchecked"? What is the reason behind those names?

LuckyLuke
  • 47,771
  • 85
  • 270
  • 434
  • 1
    What else would you call them? What's the question here? As long as you understand what 'checked' means this is not a real question. – user207421 Oct 27 '12 at 23:12

4 Answers4

14

If you call a method which is declared to throw a checked exception (such as IOException), the compiler will check that you're either catching it or declaring that you rethrow it. Likewise, in order to throw such a checked exception in the first place, the compiler checks that you've declared it as part of the method signature.

Basically, it's a little bit like type checking, except in terms of which exceptions can be thrown by a method.

The compiler doesn't perform any checking for unchecked exceptions - so they can be thrown by any method, without the method declaring them.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

Checked exceptions are checked by the Java compiler: it checks that you catch them or declare them in the method signature.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

"Checked" means that you either have to catch it or declare that your method throws it in the signature. Users of your method must catch your checked exceptions. Failure to do so will result in a compiler error.

"Unchecked" means that neither you nor users of your method are required to catch the exception. You are not required to declare it in a throws clause in your method signature.

In its earliest incarnation, Java chose the first one more often than not.

C# makes unchecked exceptions the default. Java developers have taken up that convention now, too.

duffymo
  • 305,152
  • 44
  • 369
  • 561
1

In Java you can throw any Throwable. Throwable has two sub-classes: Error and Exception. When an Error is thrown a serious problem has occured that often has very little to do with your code. Such exceptions are not checked by the compiler and is an example of an unchecked exception.

Exception has a subclass called RuntimeException, those are often exceptions that indicate bugs in your code and can often occur in lots of places in most code. Examples are NullPointerException, ArrayIndexOutOfBoundsException, etc. These are also unchecked since you would litter your code with catches of these.

All other exceptions are checked since by the compiler and you must catch or throw them.

Tobias Ritzau
  • 3,327
  • 2
  • 18
  • 29