Exception Handling in Java
Definition:
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of a program’s instruction.
Why do we need Exception Handling?
1. To separate “error handling” code from the “regular code”.
2. The programmer use exceptions to indicate that an error has occurred.
Lets see an example without
using an exception first.
Example
Package try_catch; public class Demo{ Public static void main(String[] args){ int a = 100/0; System.out.println("------------------------"); } }
Since we cannot divide any number by 0, it will throw an error as shown below in the output.
Output
java.lang.ArithmeticException: / by zero
Now, let us see an example using the try
and catch
blocks. The try
block is used to write the piece of code that might contain any exception. The catch
block then catches the exception from the try block.
Example 1
package try_catch; public class Demo{ public static void main(String[] args){ try{ int a = 100/0; } catch(ArithmeticException e){ System.out.pprintln(e); System.out.println("try block executed!"); } } }
you will get the following output:
java.lang.ArithmeticException: / by zero
try block executed!
Example 2
package try_catch; public class Demo{ public static void main(String[] args){ int b[] = new int[2]; try{ System.out.println("value of b= "+b[3]); } catch(ArrayOutOfBoundsException e){ System.out.println(e); System.out.println("------------------------"); System.out.println("Array out of bound exception!"); } } }
As shown in the above code, we have declared the array of size “2”, but we are trying to print the value of b[3]
which will throw an exception of Array out of bound!
Therefore, we write the statement which contains exception inside the try
block and it is then cought by the catch
block.
The output of the above code will look like this:
java.lang.ArrayOutOfBoundsException:
————————
Array out of bound exception!
We can add multiple try and catch blocks in the program.