Exception Hierarchy in Java
Why we can’t say Checked Exception is Compile Time Exception?
So before discuss about above concept let’s have a look on Exception Hierarchy
Here Throwable is super class of Exception and Error, And Exception divided in to 2 types which is
1. Checked Exception (Compile Time Exception)
2. Unchecked Exception (Runtime Exception)
Unchecked Exception:
The Exception which raised at Runtime even though we handle it using Try catch block it’s due to logical mistake
Ex: NullPointerException, ArrayIndexBoundException, ArithmeticException, NumberFormatException etc.
Note: we must have to handle Unchecked Exception using Try catch we can throws it
Checked Exception:
The exception which handled by compiler for smooth execution of our code. But if there is any logical mistake again then it will throw Exception at runtime itself
Ex: SQLException, FileNotFoundException, IOException etc...
Note: we can handle checked Exception using Try catch or we can use throws keyword so the end method caller need to handle it.
Here my focus is not to differentiate Checked Exception and Unchecked Exception
I want to convey here,
There is no term in java dictionary with name Compile time Exception
Unchecked exception is handled by runtime and it is Runtime exception
If you will say checked exception is handled by compiler and it is compile time exception
Let’s proof it.
Assume I have a text file in my project directory with name data.txt
Here I got compile time error, as this File IO exception is checked so we must handle it by either try catch or throws
So am going to handle it using throws keyword
Now run the code u will get runtime checked exception FileNOtFoundException think why. .?
Already as per compiler warn I handle the exception then how am getting exception? And that to be at runtime
Cause as a programmer I did mistake I specify the path name data instead of data.txt. That’s why it cause at runtime
So we can’t say checked Exception is compile Time Exception