What are checked exceptions in Java/C#?

Checked exceptions are exceptions that the compiler require you handle in some way.

In Java, checked exceptions are Throwables that are not RuntimeException, Error, or one of their subclasses.

The Java designers felt they were needed to ensure programs handled exceptions that were reasonably likely. A classic example is IOException. Any time a program does I/O, there is a possibility of failure. The disk could be full, the file might not exist, there might be a permissions problem, etc.

Thus, Java is designed such that a program must syntactically handle the exception in some way. This could be with a catch block, or by rethrowing the exception in some way.

C# does not have checked exceptions. They decided to leave this issue up to the application developers (interview). Checked exceptions are controversial because they can make code verbose, while developers sometimes handle them trivially with empty catch blocks. Further, it can be arbitrary which standard library methods throw checked exceptions. For instance, why doesn’t File.delete (a new Java 7 API does this differently) throw IOException?

Another concern Hejlsberg noted in that interview is versionability. Adding a checked exception to a throw clause forces all code using that method to be modified and recompiled.

Leave a Comment