Friday, 5 June 2015

Java Exception Handling Example

Example: This example demonstrates the action taken by the default error/exception handler when an exception/error occurs and is not handled.

class Exc0

{ public static void main(String args[])

{ int d = 0;

int a = 42/d;

System.out.println("This will not be printed");

}

}

When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. This causes the execution of Exc0 class to stop,

because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately.

In this example, we have not supplied any exception handlers of our own, so the default handler provided by the Java run-time system catches the exception. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.

Here is the output generated when this example is executed:

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

Example: This example demonstrates the action taken by the default error/exception handler when an exception/error occurs in a method other then main() and is not handled.

class Exc1

{ public static void subroutine()

{ int d = 0;

int a = 42/d;

}

public static void main(String args[])

{ Exc1.subroutine();

}

Output:

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

The resulting stack trace from the default exception handler shows how the entire call stack is displayed

System.out.println("This will not be printed");

Using try and catch

Although the default exception handler provided by the Java run-time system is useful for debugging, you will usually want to handle an exception yourself. Doing so provides two

benefits:

  • First, it allows you to fix the error
  • It prevents the program from automatically terminating

Example:

class Exc2

{ public static void main(String args[])

{ int d,a;

try

{ d = 0;

a = 42/d;

System.out.println("This will not be printed");

}

catch(ArithmeticException e)

{ //e.printStackTrace();

//System.out.println(e);

System.out.println(e.getMessage());

}

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

}

}

Output

/ by zero
After catch statement

Note: The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement. A catch statement can not catch an exception thrown by another try statement (except in the case of nested try statements). The statements that are protected by try must be surrounded by curly braces.

Example: This example demonstrates that we can continue execution after handling the exception and can execute the code of same try block again if it is part of a loop.

Recovery.java

import java.util.Random;

class HandleError

{

public static void main(String args[])

{

int a=0, b=0, c=0;

Random r = new Random();

for(int i=0; i < 5; i++)

{

try

{

b = r.nextInt();

c = r.nextInt();

System.out.println(b);

System.out.println(c);

a = 12345/ (b/c);

}catch(AirthmeticException e)

{ System.out.println(e.getMessage());

}

System.out.println("a : " + a);

}

a = 0;

}

}

Example:  The following example demonstrates the use of multiple catch clauses.

class MultiCatch

{ 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;

}

catch(ArithmeticException e)

{ System.out.println("Divide by 0: " + e);

}

catch(ArrayIndexOutOfBoundsException e)

{ System.out.println("Array Index Out Of Bound: " + e);

}

System.out.println("After try/catch blocks.");

}

}

Example: The following example throws four types of Runtime Exceptions:

  • ArithmeticException: integer division by zero.
  • NullPointerException: for accessing a field or invoking a method of a ‘null’ object.
  • ArrayIndexOutOfBoundsException: for accessing an array element by providing an index value less than zero or greater than or equal to array size.
  • StringIndexOutOfBoundsException: for accessing a character of a String or StringBuffer with index less than zero or greater than or equal to length of String.

class ExceptionTest

{ public static void main(String args[])

{ for(int i=0; i<4; i++)

{ int k = 0;

try

{ switch(i)

{ case 0: int zero = 0;

case 1: int b[] = null;

case 2: int[] c = new int[2];

case 3: char ch = "abc".charAt(3);

}

k = 911/zero;

break;

k = b[0];

break;

k = c[9];

break;

break;

}

catch (Exception e)

{ System.out.println(e);

}

}

}

}

Output:

java.lang.ArithmeticException: / by zero
java.lang.NullPointerException
java.lang.ArrayIndexOutOfBoundsException: 9
java.lang.StringIndexOutOfBoundsException: String index out of range: 3

Note: In the above example all the exceptions are handled using only one catch block. This is possible because all the exceptions are sub-classes of the Exception class.

Example: The previous example is slightly modified so that all the exceptions are handled separately. This approach allows us to take separate actions for each exception.

class ExceptionTest1

{ public static void main(String args[])

{ for(int i=0; i<4; i++)

{ int k = 0;

try

{ switch(i)

{ case 0: int zero = 0;

case 1: int b[] = null;

case 2: int[] c = new int[2];

case 3: char ch = "abc".charAt(3);

}

k = 911/zero;

break;

k = b[0];

break;

k = c[9];

break;

break;

}catch (ArithmeticException e)

{ System.out.println(e); }

catch (NullPointerException e)

{ System.out.println(e); }

catch (ArrayIndexOutOfBoundsException e)

{ System.out.println(e); }

catch (StringIndexOutOfBoundsException e)

{ System.out.println(e); }

}

}

}

Output:

java.lang.ArithmeticException: / by zero
java.lang.NullPointerException
java.lang.ArrayIndexOutOfBoundsException: 9
java.lang.StringIndexOutOfBoundsException: String index out of range: 3

Example: In case of multiple catches, exception subclasses must come before any of their super classes. This is because a catch statement that uses a super class will catch exceptions of that type plus any of its sub classes. Thus, a sub class would never be reached if it comes after its super class. Further, in java unreachable code is an error.

class ExceptionTest2

{ public static void main(String args[])

{ for(int i=0; i<4; i++)

{ int k = 0;

try

{ switch(i)

{ case 0: int zero = 0;

case 1: int b[] = null;

case 2: int[] c = new int[2];

case 3: char ch = "abc".charAt(3);

}

k = 911/zero;

break;

k = b[0];

break;

k = c[9];

break;

break;

}

catch (Exception e) //Will not compile

{ System.out.println(e);

}

catch (ArithmeticException e)

{ System.out.println(e);

}

}

}

}

Output:

ExceptionTest2.java:23: exception java.lang.ArithmeticException has already been caught

catch (ArithmeticException e)


No comments:

Post a Comment