Exception Handling

  • A system to send an error message from the place a runtime error has occurred, to the place a method get called.

  • Object -> Throwable -> Exception -> IOException, FormatException, ServletException etc.

  • Exception Handling

  • Throwable class provides common methods for all the exceptions:

    1. String getMessage()
    2. String toString()
    3. void printStackTrace()

    Exception Hierarchy
Example: WAP to input two numbers and show division of those numbers.
import java.util.*;
public class Division 
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        try
        {
            System.out.print("Number 1 : ");
            int a=sc.nextInt();
            System.out.print("Number 2 : ");
            int b=sc.nextInt();
        
            int c=a/b;
        
            System.out.printf("%d divided by %d is %d\n", a,b,c);
            
        }
        catch(InputMismatchException ex)
        {
            System.out.println("Sorry! Only Numbers are allowed");
        }
        catch(Exception ex)
        {
            //ex.printStackTrace();
            System.out.println("OOPs! An error has occured. Call on 83453453");
            System.out.println("Error Description is : "+ex.getMessage());
        }
        finally
        {
            System.out.println("Thanks for using our system");
        }
    }
}