Use of the try and catch code blocks for exception handling in Java _java

Source: Internet
Author: User
Tags exception handling

Use of Java try and catch
Although the default exception handler provided by the Java Runtime system is useful for debugging, you usually want to handle the exception yourself. There are two advantages to doing so. First, it allows you to fix errors. Second, it prevents the program from automatically terminating. Most users will be bothered to print the stack tracks at the end of the program and whenever the error occurs (at least so to speak). Luckily, it's easy to avoid.

To prevent and handle a run-time error, just put the code you want to monitor into a try block. Followed by a try block includes a catch clause that describes the type of error you want to catch. This is a simple task, and the following program contains a try block and a catch clause that handles the arithmeticexception exception that is generated by 0.

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 won't 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 calls to println () in a try block are never executed. Once an exception is thrown, the program control is transferred from the try block to the catch block. Execution will never "return" from a catch block to a try block. Therefore, "This won't be printed." ”

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

A try and its Catch statement form a unit. The scope of a catch clause is limited to the statement defined earlier in the Try statement. A catch statement cannot capture the exception that is thrown by another try declaration (unless it is a nested try statement condition).

Statement declarations that are 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 a catch clause is to resolve the exception and continue to run as if the error did not occur. For example, in the following program, each iteration of a for loop gets two random integers. The two integers are separated by each other, and the results are used to divide the 12345. The final result exists in a. If a division operation causes 0 to divide the error, it will be captured, the value of a is set to zero, and the program continues to run.

Handle an exception.
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);
    }
  }
}

Displays a description of an exception

Throwable overloaded ToString () method (defined by object), so it returns a string containing the description of the exception. You can display the description of the exception by passing an argument to the exception in println (). For example, a catch block for a previous program can 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, the program runs under the standard JAVAJDK interpreter, and each 0 error displays the following message:

  Exception:java.lang.ArithmeticException:/By zero


Although there are no special values in the context, the ability to display an exception description is valuable in other situations-especially if you are experimenting with and debugging an exception.

Use of Java multiple catch statements
In some cases, a single code fragment can cause multiple exceptions. To handle this situation, you can define two or more catch clauses, each of which captures one type of exception. When an exception is raised, each catch clause is checked sequentially, and the first matching clause of the exception type executes. When a catch statement is executed, the other clauses are bypassed and the execution of the code from the Try/catch block continues. The following example designs two different types of exceptions:

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] =;
    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 runs without the command line arguments, causing the exception to be removed by 0 because a is 0. If you provide a command-line argument, it will survive and set a to a value greater than 0. However, it will cause the Arrayindexoutof boundsexception exception because the integer array C has a length of 1 and the program attempts 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: per 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 the exception subclasses must be used before any of their parent classes. This is because the catch statement that uses the parent class captures the exception of the type and all of its subclass types. This way, if the subclass is behind the parent class, the subclass will never arrive. Also, code that cannot be reached in Java is an error. 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 would be created and acompile-time error would 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 are never reached because
    ArithmeticException is a subclass of Exception. *
    /catch (arithmeticexcept Ion e) {//error-unreachable
      System.out.println ("This is never reached.");}}

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.