Using try and catch

It is necessary to handle excdeption ourself to

  1. find out the error

  2. To avoid program from automatic termination.

To handle a run-time error simply enclose the code which we want to monitor in a try block include a catch clause that specifies the exception type that you wish to catch.

//example for using try-catch block
public class Exc2
{
 public static void main(String args[]) 
 {
 int d, a;
 try 
 {
   // monitor a block of code.
 d = 0;
 a = 42 / d;
 System.out.println("This will not be printed.");  //as exception rises it will go to the corresponding catchblock 
 }
   catch (ArithmeticException e) 
   {
     // catch divide-by-zero error
 System.out.println("Division by zero.");   

 }
 System.out.println("After catch statement.");
 }
}

Output:

Division by zero.

After catch statement.

Displaying a Description of an Exception

Throwable overrides the toString( ) method (defined by Object) so that it returns a string containing a description of the exception.

//example for displaying description of Exception by Exception object.
public class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}

catch (ArithmeticException e)
{
System.out.println("Exception: " + e);  //as e is the object which have toString() so it displays the exception
a = 0; // set a to zero and continue
}
System.out.println("After catch statement.");
}
}

Output:

Exception: java.lang.ArithmeticException: / by zero

After catch statement.

Multiple catch Clauses

In some cases there are situations where one code can throw two or more exceptions that time to handle those exceptions Multiple catch clauses can use.

// Demonstrate multiple catch statements.
public class MultipleCatches
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
System.out.println("It will not exceute");

}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);  //this is executed when b=42/a executes
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);  //c[42] = 99 as size of it is 1.
}
System.out.println("After try/catch blocks.");
}
}

Output:

a = 0

Divide by 0: java.lang.ArithmeticException: / by zero

After try/catch blocks.

If we given any command line argument

Output:

a = 1

Array index oob: java.lang.ArrayIndexOutOfBoundsException: 42

After try/catch blocks.

  • The exception subclasses must come before any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses.

  • Thus, a subclass would never be reached if it came after its superclass. Further, in Java, unreachable code is an error.

//example for Super Exception class and Sub Exceptions using
public class SuperSubCatch
{
public static void main(String args[])
{
try
{
int a = 0;
int b = 42 / a;
}
catch(Exception e)
{
System.out.println("Generic Exception catch."); //Exception is the super class of ArthimeticException,Subclassshould be first
}

/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e)
{ // ERROR – unreachable
System.out.println("This is never reached.");
}
}
}

Output:

Unable to execute program; could not compile!

Nested try Statements

One try statement inside another try statement.

// An example of nested try statements.
public class NestTry 
{
 public static void main(String args[]) 
 {
 try
 {
 int a = args.length;
 /* If no command-line args are present,
 the following statement will generate
 a divide-by-zero exception. */
 int b = 42 / a;
 System.out.println("a = " + a);
 try 
 { 
   // nested try block
 /* If one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */

   if(a==1)
     a = a/(a-a); // division by zero

   /* If two command-line args are used,
 then generate an out-of-bounds exception. */
 if(a==2) 
 {
 int c[] = { 1 };
 c[42] = 99; // generate an out-of-bounds exception
 }
 }
   catch(ArrayIndexOutOfBoundsException e) 
   {
 System.out.println("Array index out-of-bounds: " + e);
 }
 } 
   catch(ArithmeticException e) 
   {
 System.out.println("Divide by 0: " + e);
 }
 }
}

Output:

Divide by 0: java.lang.ArithmeticException: / by zero (if no command line arguments)

a = 1
Divide by 0: java.lang.ArithmeticException: / by zero (if one command line argument)

a = 2
Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException: 42 (if two command line arguments)

Nested try can occur while calling a method in side a try block which have a try block as follows

/* Try statements can be implicitly nested via calls to methods. */
public class MethNestTry 
{
 static void nesttry(int a) 
 {
 try 
 { 
   // nested try block

 if(a==1) a = a/(a-a); // division by zero

   // If two command-line args are used, then generate an out-of-bounds exception. 
 if(a==2) 
 {
 int c[] = { 1 };
 c[42] = 99; // generate an out-of-bounds exception
 }
 } 
   catch(ArrayIndexOutOfBoundsException e) 
   {
 System.out.println("Array index out-of-bounds: " + e);
 }
 }

 public static void main(String args[])
 {
 try 
 {
 int a = args.length;
 //If no command-line args are present, the following statement will generate a divide-by-zero exception. 

   int b = 42 / a;
 System.out.println("a = " + a);
   nesttry(a);
 } 
   catch(ArithmeticException e) 
 {
 System.out.println("Divide by 0: " + e);
 }
 }
}

results matching ""

    No results matching ""