What are checked exceptions in Java/C#?
I am a C# developer doing occasional coding in Java. Can someone explain in simple terms what are checked exceptions in Java and why is it needed? Haven't come across this term in C#.
Checked exceptions are exceptions that the compiler require you handle in some way.
In Java, checked exceptions are Throwable
s 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.
In Java, a checked exception (as Matthew Flaschen correctly points out) is an exception that the compiler requires you to handle. These are exceptions that are declared on function definitions (e.g. function bob() throws ImNotBobException { ... }
to say that calling that function may throw that exception - e.g. NumberFormatException
when parsing an integer, or IOException
when writing to a file.
However, some exceptions can be thrown from unknown or unexpected places that are simply impractical to handle on every level, so the compiler does not require you to handle these. These are unchecked exceptions. They can be thrown from various places that do not declare to throw them (often by attempting to call a method on an object when that object has not been initialised yet, i.e. is null - this will result in a NullPointerException
.)
Hope this helps.