Reading about Exceptions in this book, I found this statement:
Checked exceptions are checked by the compiler at compile time.
and
The compiler does not check unchecked exceptions at compile time.
So, if also we can say that IOException
or SQLException
are below the Checked Exceptions class tree. How would java compiler know there will be an exception and no for IllegalArgumentException
which might remain inside the code as my understanding.
Also, what does exactly the fact of being obligatory to get the Checked exceptions caught and not for Unchecked mean?
exceptions in java all work the same way.
the difference between checked and unchecked exceptions (which are all subclasses of RuntimeException) if that for a method that throws a checked exception whoever calls that method has to either try/catch the exception, or declare his own method as throwing that exception.
so if i have a method:
void throwsACheckedException() throws SomeCheckedException;
whoever calls it must do one of 2 things. either:
try {
throwsACheckedException();
} catch (SomeCheckedException e) {
//do something
}
or
void someCallingMethod() throws SomeCheckedException { //pass it on
throwsACheckedException();
}
unchecked exceptions you dont have to declare, and whoever calls the method does not have to explicitly catch. for example:
void someInnocentLookingMethod() {
throw new NullPointerException("surprise!"); //...extends RuntimeException
}
and then you can simply invoke it, without the try/catch hassle:
void unsuspectingVictim() {
someInnocentLookingMethod();
}
unchecked exceptions are usually used for things that can creep up on you at any point and so forcing developers to try/catch them would make the code very tedious (NullPointerException, for example), although there are those who thing checked exceptions are evil entirely :-)
A checked exception requires that you add a throws
declaration to the method signature, or you add a try
catch
block around it.
public void checked() throws IOException {
throw new IOException(); // compiles just fine
}
public void checked() {
try {
throw new IOException();
} catch (IOException e) {
// ...
}
}
This will not work:
public void checkedWithoutThrows() {
throw new IOException(); // will not compile
}
An unchecked exception does not need this.
public void unchecked() {
throw new RuntimeException();
}
And, just for completeness, the way to determine unchecked from checked exceptions is that unchecked exceptions all descend from RuntimeException
at some point or another.
For Checked exceptions, you see error at compile time and says that you have to handle them.
Run time exceptions do not give any error or warning to handle in your code.
Compiler expects exceptions (Checked exceptions) and asks you to handle it.