
Exception Handling in Java
Exception Handling in Java
Definition
Error – Handling becomes a necessary while developing a application to account for exceptional satiations that may occur during the program executions.
Exception can be generated by Java-run time system or they can be manually generated by code.
Types of Exception:
- Checked Exception
- Un-Checked Exception
Checked Exception:
Checked exception must be handled at compile time.
Un-Checked Exception:
Un-Checked exception must be handled at Run time.
Program:
public class ArithmeticExceptionDemo { public static void main(String[] args) { int x=100; int y=0; int z=x/y; System.out.println("z"+z); } } |
Output:
Exception in thread “main” java.lang.ArithmeticException: / by zero
Implement the exception handling:
public class ArithmeticExceptionDemo { public static void main(String[] args) { int x=100; int y=0; try{ int z=x/y; System.out.println("z"+z); }catch(ArithmeticException e){ System.out.println (" x is not divided by zero"); } } } |
Output:
x is not divided by zero |
public class ArrayIndexOutExceptionDemo { public static void main(String[] args) { int [] inputArray={0,1,2}; int k=0; for(int i=0; i < inputArray.length;i++){ int j = inputArray[i] + inputArray[i+1]; System.out.println("J"+j); } } } |
Output:
J1
J3 Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 3 |