Understanding Exception and Exception Handling
If we develop the application without exception handling then probably we should think of leaving our developer job and look out for something else.
Yes, no matter whether clients asks or not, we need to identify unexpected behaviours and we need to handle them using exception handling in Java.
Let’s understand what is “ Exception ”
Exception is an unexpected event which interrupts the further execution of the program.
In Java, each of such unexpected events are represented by an object of “ Exception ” class.
So whenever unexpected event occurs, Java throws one object of Exception class and
stop the further execution of the program.
Since Java records each of these unexpected events and throws an object, it becomes very easy to handle such behaviours.
What is Exception Handling?
Exception handling is a powerful mechanism in Java which helps us to continue the further execution of the program even if unexpected event occurs in our application.
So, we are going to handle any unexpected behaviour and make sure that program continues its execution in the same way as if such unexpected behaviour has not happened.
We can handle exceptions in any one of the 2 ways listed below
1) Using try-catch
2) Using throws
Why an Exception occurs?
Exception occurs because of various reasons which includes giving bad input or reading from a non-existing file, trying to connect to database but database
server is down.
Sometimes it happens with bad programming also, we will see what best practice we need to follow so that we can avoid such exceptions.
Types of Exception
1) Checked or compile time exception
2) Unchecked or Runtime exception
Exceptions are broadly classified as “ Checked ” and “ Unchecked ” based on whether Java compiler force the programmer to handle exception or not.
Checked ExceptionChecked exceptions are also called “ compile Time exceptions ” Those exceptions which compiler checks during the compilation to see whether they are handled or not. If they are not handled, compiler will force us to handle and until we handle it, we get compile time error and we can’t proceed further. Since compiler “ checks ” for these exceptions to make sure that they are handled, it is called Checked exception. Example: IOException, SQLException
Unchecked ExceptionUnchecked exceptions are also called “ Run Time exceptions ” These exceptions will not be checked by compiler to see whether programmer has handled or not. But it’s the programmer responsibility to handle these exceptions. Example: NullPointerException, ArithmeticException