Java Exception Handling



Exception Handling in Java Programming :

  1. An exception is an event.
  2. Exception occurs during the execution of a program when normal flow of the program is Interrupted or disturbed.
  3. Exception Handling is machanism to handle the exceptions.

How Exception Handling Works in Java ?

  1. When any error occures in a method then new object (i.e Exception Object) is created by a method
  2. Exception Object contain information about error such as type of error and state of the program.
  3. Newly created exception object is passed to the Runtime System.
  4. Runtime system will handle the exception to keep system stable

Advantages of Exception Handling :

In the previous programming languages, whenever any illegal condition is executed then program flow gets disturbed. In java programming exception handling ensures that program should run smoother. Consider the following example –

public class ExceptionExample {
    public static void main(String[] args) {
       int num1 = 50;
       int num2 = 0;
       int ans;

       ans = num1 / num2;
       System.out.println("Result of Division : " + ans);
   }
}

In this example, we know that any number divided by 0 will cause program to go into unexpected situation. If program contain such unexpected statements then its better to handle these unexpected results. Below is the unexpected error output –

Exception in thread "main" java.lang.ArithmeticException: / by zero
      at DivideByZeroNoExceptionHandling.main(
           DivideByZeroNoExceptionHandling.java:7)

Now we have done slight modification in the program by providing exception handling code in the program –

public class ExceptionExample {
    public static void main(String[] args) {
       int num1 = 50;
       int num2 = 0;
       int ans;
       try { 
   	    ans = num1 / num2;
	    System.out.println("Result of Division : " + ans);
	} catch(ArithmeticException e) {
	    System.out.println("Divide by Zero Error");
	}   
   }
}

so the output of the above code will be –

Divide by Zero Error