What is Exception Handling in java?
In this post, we will learn about the Exceptions and type of exceptions.
What is an Exception?
An exception can be anything which interrupts the normal flow of the program.If an error occurs, execution of the program will be stopped and system will throw an error message about the exceptions.These exceptions can be handled, how to handle them we will discuss it later.
When these exceptions can occurs?
These exceptions can occur at run time time called as RunTime Exceptions and at compile time known as Compile Time exceptions. Exceptions can occur at any step in the program. Suppose, we have 15 lines of program and exception occurs at 5th line. Then code after the 5th line will not be executed.
Code line - 1 Code line - 2 Code line - 3 Code line - 4 Code line - 5 //Exception occurs Code line - 6 Code line - 7 * * * Code line - 15
Can we Handle Exceptions?
We have a mechanism to handle these exceptions which is called Exception Handling. It is nothing but to handle the run time exceptions like IO exceptions, SQL exceptions, ClassNotFound exceptions etc.
Advantages of Exception Handling:
- As we have seen the above example, if we use proper exception handling in the program. Then we can capture the exception and continue executing the rest of the code if required.
- We can print a user friendly message as per the requirement.
Types of Exceptions:
There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions:
- Checked Exceptions
- Unchecked Exceptions
Hierarchy of Exceptions Classes in java:
What are these checked and unchecked Exceptions?
1. Checked Exceptions:
Exception other than RunTime exceptions are known as Checked Exceptions.These are checked at compile time. These error will force the programmer to handle these error either by using Throws keyword or try-catch block.
Examples of Checked Exceptions:
- NoSuchFieldException etc.
2. Unchecked Exceptions:
These exceptions are checked at Runtime rather than at compile time, that’s why known as Runtime exceptions or Unchecked Exception. A programmer should handle these error to find a safe exit during execution of the program , if any error occurs.It could be thrown due to incorrect logic of the program etc.
Example of Unchecked Exceptions:
- NullPointerException etc.
Common scenarios where exceptions may occur:
If any variable has null value and we perform some operation on that variable, NullPointerExceptions will be thrown.
String s=null; System.out.println(s.length());//NullPointerException
If we divide any number by zero, there occurs an ArithmeticException.
If we try to access the index of array which does not exist, throws ArrayIndexOutOfBoundsException .
int a=new int; a=10; //ArrayIndexOutOfBoundsException