Wednesday, February 15, 2012

Using try, catch, and finally blocks

Java's exception-handling code is specified within a try...catch...finally block.


The try block encloses the code that might cause an exception to occur. The code in the try block is called protected code.
// basic try statement syntax
try {
  // protected code
}
catch (ExceptionType1 Identifier1) {
  // exception-handling code
}
catch (ExceptionType2 Identifier2) {
  // exception-handling code
}

finally {
  // 0 or 1 finally clause
}
You use zero or more catch blocks. When present, catch blocks specify exception handlers for the types of exceptions thrown. If no exception is thrown, then the code in the catch block doesn't run because it isn't needed.
The finally block is optional if a try block already has an associated catch block. If you have a finally block, the code it contains always executes, regardless of whether exceptions are thrown or not. The only exception to this rule is if a System.exit occurs, in which case the application terminates without executing a finally block.
If an exception occurs in a try block and is not caught in a catch block, a finally block will execute, provided it is present. The application then terminates.

If required, you must explicitly throw the exception up the call stack. If no method handles the exception, the program terminates when the exception object reaches the top of the call stack.
Consider the code in which the tryValues method contains appropriate exception-handling code.

The method takes two parameters – x and y. It declares and initializes an array and then prints the value of each array element divided by y, within a loop.
public class TestExceptions {

  // Catch the exceptions within the method itself
  void tryValues (int x, int y) {

    boolean wasError = false ;
    int[] intArray = new int[5] ;
    for (int i=0; i < intArray.length - 1; i++ )
      { intArray[i] = i + 8 ; }
    try {
      for (int i = 0; i <= x - 1; i++) {
        System.out.println (intArray[i] / y) ;
      }
    }
    //...
You enclose any lines of code that could cause exceptions in a try block.

For example, an exception could be caused if x is larger than the size of the array, or y is equal to zero.
public class TestExceptions {

  // Catch the exceptions within the method itself
  void tryValues (int x, int y) {

    boolean wasError = false ;
    int[] intArray = new int[5] ;
    for (int i=0; i < intArray.length - 1; i++ )
      { intArray[i] = i + 8 ; }
    try {
      for (int i = 0; i <= x - 1; i++) {
        System.out.println (intArray[i] / y) ;
      }
    }
    //...
If an exception occurs in a try block, execution is immediately directed to a series of catch blocks following the try block, which include the error-handling code.

Generally, you include a catch block for each type of exception that might be thrown in the try block, although you can write a single catch block for all exceptions if you like. You should aim to catch and handle specific exceptions, rather than general ones.
try {
  for (int i = 0; i <= x - 1; i++) {
    System.out.println (intArray[i] / y) ;
  }
}
catch (ArrayIndexOutOfBoundsException e) {
  System.out.println ("Array bounds exceeded" ) ;
  wasError = true ;
}
catch (ArithmeticException e) {
  System.out.println ("Attempt to divide by zero" ) ;
  wasError = true ;
}
catch (Exception e) {
  System.out.println ("Unknown exception occurred: " + e) ;
  wasError = true ;
}
finally {
  if (wasError)
    System.out.println ("Ending tryValues with error" ) ;
  else
    System.out.println ("Ending tryValues without an error" ) ;
}
If an exception occurs, the catch blocks are checked in order, from top to bottom.

If the exception is of the appropriate type for one of the catch blocks, the statements within the catch block are executed and no further catch blocks are checked. So the order in which you position catch blocks is important.

2 comments:

I just see the post i am so happy to the communication science post of information's.So I have really enjoyed and reading your blogs for these posts.Any way I’ll be replay for your great thinks and I hope you post again soon...
Web Development Company in India

Post a Comment