Question: Write a detailed note on Exception Handling in terms of following:
0

1)Try-catch

2)Finally keyword

3)Catching multiple exception

4)Throwing exception

Marks: 10 M

Year: Dec 2013, Dec 2014

ADD COMMENTlink
modified 3.1 years ago  • written 3.1 years ago by gravatar for Sayali Bagwe Sayali Bagwe2.1k
0

1) Try-Catch:

  • In java, Exception handling is implemented using Try-catch. It provides two benefits
    • It allows us to fix the errors.
    • It prevents the program from automatically terminating.
  • The general syntax of Try-catch is as follows:

    try
    {
    // block of code to monitor for errors
    }
    catch (ExceptionType1 exOb)
    {
    // exception handler for ExceptionType1
    }
    catch (ExceptionType2 exOb)
    {
    // exception handler for ExceptionType2
     } 
    //.......
    
  • Here, ExceptionType is the type of exception that has occurred and exOb.

  • The keyword try is used to preface a block of code that is likely to cause an error condition and throw an exception.
  • The catch block catches the exception thrown by the try block and handles it appropriately.
  • The catch block is added immediately after the try block. A try and its catch statement form a unit.
  • The scope of the catch clause is restricted to those statements specified by the immediately after try statement.
  • A catch statement cannot catch an exception thrown by another try statement. The statements that are protected by try must be surrounded by curly braces.
  • The goal of most well-constructed catch clauses should be to resolve the exceptional condition and then continue on as if the error had never happened.

2) Finally Keyword:

  • The finally is a block of code after try/catch block that will be executed after a try/catch block has completed and before the code following the try/catch block.
  • The finally block will execute whether an exception is thrown or not. If an exception is thrown, the finally block will execute even if no catch statement matches the exception.
  • If any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns.
  • This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method.
  • The finally clause is optional. But, each try statement requires at least one catch or a finally clause.
  • The try-catch-finally of try-finally construct can be created as,

    try
    {
     .......
     }
     catch(....) //multiple catch are allowed
     {
      .......
      }
      finally
      {
       .......
       }
    

    OR

      try
      {
      .......
      }
     finally
     {
      .......
      }
    
  • The program below illustrates use of finally keyword:

     //Use of finally statement
     class FinallyClause
     {
     public static void main(String args[])
    {
        try
    {
        //int val = 0; //statement1
        //int m = 100 / val; //statement2
            int []x = new int[-5]; //statement3
        System.out.println("No output");
    }
    catch(ArithmeticException e)
    {
        System.out.println("Exception: "+e);
    }
    finally
    {
        System.out.println("Program end");
        System.out.println("Bye bye...");
              }
         }
    }
    
      Output:
      Program end
      Bye bye...
      Exception in thread "main"
      java.lang.NegativeArraySizeException
      at FinallyClause.main(FinallyClause.java:10)
    
  • In program, the exception of “negative array size” has occurred at ststement3. But the catch statement will not catch it as only ArithmeticException is mentioned there. So the program will be terminated. But before its termination and printing the stack trace, the finally block is executed.

3) Catching multiple exception

  • In some cases, more than one exception may occur in a single program.
  • In order to handle this type of situation, we can specify two or more catch statements in a program. Each ‘catch’ will catch a different type of exception.
  • When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block.
  • The following example traps two different exception types:

    // Using multiple catch statements
    import java.util.Scanner;
    class MultiCatch
    {
    public static void main(String args[])
    {
    int x,z;
    Scanner in = new Scanner(System.in);
    System.out.print("Enter number : ");
    x = in.nextInt();
    try
    {
            z = 50 / x; //statement1
        System.out.println("Division: "+z);
            short arr[] = {5,7,8};
        arr[10] = 120; //statement2
            System.out.println("Try end...");
    }
    catch(ArithmeticException e)
    {
        System.out.println("Division by zero");
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
        System.out.println("Array indexing wrong");
    }
    System.out.println("Program end...");
    }//end of main()
    }//end of class
    
    
    Output:
    Enter number: 0
    Division by zero
    Program end...
    Enter number: 5
    Division: 10
    Array indexing wrong
    Program end...
    

4) Throwing exception

  • Java has defined a lot of Exception and Error classes for different conditions.
  • But many times it is required in some conditions that we want to create your own exception types to handle situations specific to our applications.
  • We just have to define a subclass of Exception, which is a subclass of Throwable.
  • Our subclasses don’t need to actually implement anything. It is their existence in the type system that allows us to use them as exceptions.
  • The Exception class does not define any methods of its own. It inherits all the methods provided by class Throwable. Thus, all exceptions, including those that we create, have the methods defined by Throwable available to them. In order to create our own exception we

need to derive our class from Exception.

// Creating our own exception.
class NegativeOutputException extends Exception
{
private int det;
NegativeOutputException(int a)
{
    det = a;
}
public String toString()
{
    return "NegativeOutputException["+det+"]";
}
}
class OwnException
{
public static void main(String args[])
{
    int x = Integer.parseInt(args[0]);
    int y = Integer.parseInt(args[1]);;
    int z;
    try
    {
        z = x * y;
        if(z<0) //statement1
        throw new NegativeOutputException(z);
        System.out.println("Output: "+z);
    }
    catch (NegativeOutputException e)
    {
        System.out.println("Caught: "+e);
    }
}
}

Output:
java OwnException 4 8
Output: 32
java OwnException 4 -3
Caught: NegativeOutputException[-12]
java OwnException -4 -3
Output: 12
ADD COMMENTlink
modified 3.1 years ago  • written 3.1 years ago by gravatar for Sayali Bagwe Sayali Bagwe2.1k
Please log in to add an answer.