Uses of Exception Handling:

 

  • We can know in which part of the program the logical error has actually occurred.
  • We are not allowing the JVM to terminate the entire program. Only the try block in which the error has occurred would be terminated.
  • Thus, this is an easy way of debugging the program.
  • Once control enters the catch block, it executes the statements in catch block and moves on further. It will not come back to the try block because of which the catch block was executed.
  • If no exception class object is created in the try block, control will never enter the catch block.
  • Every try block should be associated with at least one catch block.
  •  A try block can have any number of catch blocks.

 

Example program:

Class A

{

Fun A ()

{

System. Out. Prinln(“fun A ()”);

}

Class EDemo1

{

Public static void main (string args [ ])

{

Int   i    = Integer .parse Int (args [0]);

Int   j    = Integer .parse Int (args [1]);

Int   k    = Integer .parse Int (args [2]);

Int   L   = Integer .parse Int (args [3]);

A a1 = null;

Try

{

System. Out. Prinln(“ inside try block”);

Int x = i/j;

System. Out. Prinln(x);

Int ar1 [] = new int [k];

Ar1 [L] = x;

If (x>10)

a1 = new A ();

a1. Fun A ();

System. Out. Prinln(“ end of  try block”);

}

Catch (Arithmetic exception e1)

{

System. Out. Prinln(e1);

}

Catch ( Array Index out of Bounds Exception e2)

{

System. Out. Prinln(e2);

}

Catch (null pointer exception e3)

{

System. Out. Println (e3);

}

System. Out. Prinln(i);

System. Out. Prinln(j);(

System. Out. Println (k);

System. Out. Prinln(L);

}

}

For each and every statement in the try block which is proven to generate an exception class object, there should be a corresponding catch block.

 


Disadvantages of this approach

  • If statements in the try block are more that generate the exception class object, then we should have those many catch blocks which is not feasible.
  • The user should have through knowledge regarding, what statement is proven to generate what type of exception class object. At times, this would be very difficult.

 

Uses of Exception Handling Homework Help