Home  >  Article  >  Java  >  The use of try and catch code blocks for exception handling in Java

The use of try and catch code blocks for exception handling in Java

高洛峰
高洛峰Original
2017-01-18 15:01:521619browse

Usage of Java try and catch
Although the default exception handlers provided by the Java runtime system are useful for debugging, usually you want to handle exceptions yourself. This has two benefits. First, it allows you to correct errors. Second, it prevents the program from terminating automatically. Most users are annoyed (to say the least) by having a stack trace printed when the program terminates and whenever an error occurs. Fortunately, this is easily avoidable.

To prevent and handle a runtime error, just put the code you want to monitor into a try block. Immediately following the try block, include a catch clause that specifies the type of error you wish to catch. Accomplishing this task is simple. The following program contains a try block and a catch clause that handles ArithmeticException exceptions caused by division by zero.

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) { // catch divide-by-zero error
      System.out.println("Division by zero.");
    }
    System.out.println("After catch statement.");
  }
}

The program output is as follows:

Division by zero.
After catch statement.

Note that the call to println() in the try block is never executed. Once an exception is raised, program control is transferred from the try block to the catch block. Execution never "returns" from the catch block to the try block. Therefore, "This will not be printed."

will not be displayed. Once the catch statement is executed, program control continues from the line below the entire try/catch mechanism.

A try and its catch statement form a unit. The scope of the catch clause is limited to the statements defined before the try statement. A catch statement cannot catch an exception raised by another try statement (except in the case of nested try statements).

Statement declarations protected by try must be within a curly brace (that is, they must be in a block). You cannot use try alone.

The purpose of constructing the catch clause is to resolve the exception and continue running as if the error did not occur. For example, in the following program, each iteration of the for loop yields two random integers. These two integers are divided by each other, and the result is used to divide 12345. The final result is stored in a. If a division operation results in a divide-by-zero error, it is caught, the value of a is set to zero, and the program continues.

// Handle an exception and move on.
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<32000; i++) {
      try {
        b = r.nextInt();
        c = r.nextInt();
        a = 12345 / (b/c);
      } catch (ArithmeticException e) {
        System.out.println("Division by zero.");
        a = 0; // set a to zero and continue
      }
      System.out.println("a: " + a);
    }
  }
}

Display an exception description

Throwable overloads the toString() method (defined by Object), so it returns a string containing the exception description. You can display a description of an exception by passing it a parameter in println(). For example, the catch block of the previous program could be rewritten as

catch (ArithmeticException e) {
  System.out.println("Exception: " + e);
  a = 0; // set a to zero and continue
}

When this version replaces the version in the original program and the program is run under the standard javaJDK interpreter, each divide-by-zero error displays the following message:

Exception: java.lang.ArithmeticException: / by zero

Although it has no special value in context, the ability to display an exception description can be valuable in other situations - especially when you are experimenting and debugging exceptions.

Use of Java multiple catch statements
In some cases, multiple exceptions may be caused by a single code segment. To handle this situation, you can define two or more catch clauses, each catching a type of exception. When an exception is raised, each catch clause is checked in turn, and the first one matching the exception type is executed. When a catch statement is executed, other clauses are bypassed and execution continues from the code after the try/catch block. The following example designs two different exception types:

// Demonstrate multiple catch statements.
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 oob: " + e);
    }
    System.out.println("After try/catch blocks.");
  }
}

The program is run under the starting condition without command line parameters, resulting in a divide-by-zero exception because a is 0. If you provide a command line argument, it will survive and set a to a value greater than zero. But it will cause an ArrayIndexOutOf BoundsException exception because the length of the integer array c is 1 and the program tries to assign a value to c[42].

The following is the output of the program running in two different situations:

C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks.
C:\>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException After try/catch blocks.

When you use multiple catch statements, it is important to remember that exception subclasses must be used before any of their parent classes. of. This is because using the catch statement of the parent class will catch exceptions of this type and all its subclasses. This way, if the child class is behind the parent class, the child class will never arrive. Moreover, unreachable code in Java is a bug. For example, consider the following program:

/* This program contains an error.
A subclass must come before its superclass in a series of catch statements. If not,unreachable code will be created and acompile-time error will result.
*/
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.");
    }
    /* This catch is never reached because
    ArithmeticException is a subclass of Exception. */
    catch(ArithmeticException e) { // ERROR - unreachable
      System.out.println("This is never reached.");
    }
  }
}

If you try to compile this program, you will receive an error message stating that the second catch statement will not arrive because the exception has already been caught. Because ArithmeticException is a subclass of Exception, the first catch statement will handle all Exception-oriented errors, including ArithmeticException. This means the second catch statement will never execute. To modify the program, reverse the order of the two catch statements.

For more articles related to the use of try and catch code blocks for exception handling in Java, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn