Get a complete picture of how to capture exceptions in Java _java

Source: Internet
Author: User
Tags finally block

1. Try-catch statement

In Java, exceptions are caught by Try-catch statements. Its general grammatical form is:

The try { 
  //The program code that may have an exception can 
catch (Type1 id1) { 
  //catch and dispose of the exception type thrown by a try Type1 
} 
catch (Type2 id2) { 
   // Catch and dispose of the exception type Type2} Thrown by try 

A pair of curly braces after the keyword try packs a piece of code that may have an exception, called the monitoring area. An exception object is created when the Java method occurs during the run. Throwing exceptions out of the monitoring area, the Java Runtime system attempts to find a matching catch clause to catch the exception. If there is a matching catch clause, the exception handling code is run and the Try-catch statement ends.

The principle of matching is that if the exception object thrown is an exception class for a catch clause, or a subclass of the exception class, the resulting exception object is considered to match the type of exception caught by the catch block.

Example 1 captures the "divisor 0" exception thrown by the throw statement.

public class TestException {public 
  static void Main (string[] args) { 
    int a = 6; 
    int b = 0; 
    try {//try-Monitor area 
        
      if (b = = 0) throw new ArithmeticException ()//Throw an exception through the throw statement 
      System.out.println ("A/b value is:" + A/ b); 
    } 
    catch (ArithmeticException e) {//Catch catch Exception 
      System.out.println ("program exception, variable B cannot be 0.") "); 
    } 
    SYSTEM.OUT.PRINTLN ("The program ends normally.) "); 
  } 
}

Run Result:

The program has an exception and variable B cannot be 0. The

program ends normally.

Example 1 is judged by the IF statement in the try monitoring area, when the "divisor 0" error condition is set up to cause the arithmeticexception exception, creates the ArithmeticException exception object, and throws the exception to the Java Run-time system by the throw statement, The system looks for a matching exception handler catch and runs the corresponding exception handling code, the printout "program is abnormal, and variable B cannot be 0." The Try-catch statement ends and the program flow continues.

In fact, the "divisor is 0" and so on ArithmeticException, is the Runtimexception subclass. Runtime exceptions are automatically thrown by the Run-time system and do not require the use of throw statements.

Example 2 captures the ArithmeticException exception thrown by a "divisor of 0" when the runtime system automatically throws.

public static void Main (string[] args) { 
    int a = 6; 
    int b = 0; 
    The try {System.out.println ("A/b" 
      value is: + A/b); 
    } catch (ArithmeticException e) { 
      System.out.println ("program exception, Variable B cannot be 0. "); 
    } 
    SYSTEM.OUT.PRINTLN ("The program ends normally.) "); 
  } 
}

Run Result:

The program has an exception and variable B cannot be 0. The

program ends normally.

The statement in Example 2:

System.out.println ("A/b value is:" + A/b);

A "divisor 0" error occurred in the run, throwing a ArithmeticException exception. The runtime system creates an exception object and throws the monitoring area, which in turn matches the appropriate exception handler catch and executes the appropriate exception handling code.

Because the cost of checking for run-time exceptions is much greater than the benefits of catching exceptions, runtime exceptions are not available. The Java compiler allows a run-time exception to be ignored, and a method can neither capture nor declare a Run-time exception.

Example 3 does not capture or declare a Run-time exception to throw.

public class TestException {public 
  static void Main (string[] args) { 
    int A, b; 
    A = 6; 
    b = 0; The value of divisor B is 0 
    System.out.println (A/b); 
  } 
}

Run Result:

Exception in thread ' main ' java.lang.ArithmeticException:/by zero at
Test.TestException.main (Testexception.java 78D

The example 4 program may have a divisor of 0 exceptions and an array subscript out of bounds.

public class TestException {public 
  static void Main (string[] args) { 
    int[] Intarray = new Int[3]; 
    try {for 
      (int i = 0; I <= intarray.length; i++) { 
        intarray[i] = i; 
        System.out.println ("intarray[" + i + "] =" + intarray[i]); 
        System.out.println ("intarray[" + i + "] modulo" + (i-2) + "value:" 
            + intarray[i]% (i-2)); 
      } 
    catch (ArrayIndexOutOfBoundsException e) { 
      System.out.println ("Intarray array subscript bounds exception.) "); 
    } catch (ArithmeticException e) { 
      System.out.println ("divisor is 0 exception.") "); 
    } 
    SYSTEM.OUT.PRINTLN ("The program ends normally.) "); 
  } 
}

Run Result:

Intarray[0] = 0

intarray[0] modulo-2 value: 0

intarray[1] = 1

intarray[1] modulo-1 value: 0

intarray[2] = 2

Divisor is 0 exception.

The program ends normally.

Example 4 program may have a divisor of 0 exception, and may also appear array subscript out of bounds exception. The ArithmeticException exception type is first matched during program operation, so a matching catch statement is executed:

catch (ArithmeticException e) { 
   System.out.println ("divisor is 0 exception.") "); 
 }

It should be noted that once a catch catches a matching exception type, it enters the exception handling code. At the end of the process, it means that the entire Try-catch statement ends. Other catch clauses no longer have the opportunity to match and catch the exception type.

Java describes the type of exception through an exception class, and the hierarchy of the exception classes is shown in Figure 1. For exception programs with multiple catch clauses, you should try to put the catch clause of the underlying exception class in front of you as much as possible, and then try to put the catch clause of the exception class that captures the relatively high level behind. Otherwise, catch clauses that capture the underlying exception class may be masked.

The runtimeexception exception class includes various common exceptions to the runtime, ArithmeticException classes and ArrayIndexOutOfBoundsException classes are its subclasses. Therefore, the catch clause of the RuntimeException exception class should be put on the last side, or it may mask specific exception handling or cause compilation errors.

2. try-catch-finally statement

The Try-catch statement can also include the third part, which is the finally clause. It indicates what should be done, regardless of whether an exception occurs. The general grammatical form of a try-catch-finally statement is:

try { 
  //possibly Exception program code 
} catch (Type1 id1) { 
  //catch and handle the exception type thrown by a try Type1 
} catch (Type2 id2) { 
  //capture and process a try The thrown exception type Type2 
} finally { 
  //the statement block that will be executed, regardless of whether an exception occurs 

Example 5 an exception handler with a finally clause.

public class TestException {public 
  static void Main (String args[]) { 
    int i = 0; 
    String greetings[] = {' Hello world! ', ' Hello World!! ', 
        ' Hello World!!! '}; 
    while (I < 4) { 
      try { 
        //pay special attention to the design of the loop control variable i, avoid causing infinite loop 
        System.out.println (greetings[i++]); 
      ArrayIndexOutOfBoundsException e) { 
        System.out.println ("array subscript out of bounds exception"); 
      } finally { 
        System.out.println ( "--------------------------"); 
      } 
    } 
  } 
}

Run Result:

Hello World!

———————— –

Hello World!!

———————— –

HELLO World!!!

———————— –

The array subscript crosses an exception

————————-

In Example 5, pay special attention to the design of the statement block in the TRY clause and, if designed as follows, there will be a dead loop. If the design is:

try { 
   System.out.println (greetings[i]); i++; 
}

Summary:

Try block: Used to catch exceptions. 0 or more catch blocks can then be followed, and if there are no catch blocks, you must follow a finally block.
Catch block: Used to handle an exception that is caught by a try.
Finally block: The statements in the finally block are executed whether or not the exception is captured or handled. When a return statement is encountered in a try block or a catch block, the finally statement block is executed before the method returns. Finally blocks are not executed in the following 4 special cases:
A. An exception occurred in the finally statement block.
B. System.exit () exits the program in the preceding code.
C. The thread of the program is dead.
D. Turn off the CPU.

3. Try-catch-finally rules (syntax rules for exception handling statements):

A. A catch or finally block must be added after a try. A try block can be followed by both catch and finally blocks, but at least one block.
B. The block order must be followed: If the code uses both catch and finally blocks, the catch block must be placed after the try block.
C. The catch block is related to the type of the corresponding exception class.
D. A try block may have more than one catch block. If so, the first matching block is executed. That is, the Java Virtual Opportunity matches the exception type that is actually thrown in sequence with each catch code block, and executes the catch code block if the exception object is an instance of an exception type or its subclass, and no additional catch code blocks are executed.
E. Nested try-catch-finally structures.
F. In the try-catch-finally structure, you can throw the exception again.
G. The implementation finally end is always terminated except for the JVM prematurely (calling system.exit (int)), throwing an unhandled exception in the finally block, the computer powering down, burning, or encountering a virus attack.

4. Execute order of try, catch, finally statement blocks:

A. When a try does not catch an exception: the statements in the TRY statement block are executed individually, and the program skips the catch statement block, executing the finally statement block and subsequent statements;

B. When try catches an exception, there is no handling of this exception in the Catch statement block: When a statement in a try statement block has an exception, and there is no catch statement block that handles the exception, the exception is thrown to the JVM, and the statement in the finally statement block is executed, but the statement after the finally statement block does not be carried out;

C. When try catches an exception, there is a case in the catch statement block that handles this exception: executes in order in the TRY statement block, and when an exception is executed to a statement, the program jumps to the catch statement block and matches the catch statement block one at a time to find the handler that corresponds to it, and the other catch statement blocks are not Row, and in the try statement block, the statement after the exception is not executed, the CATCH statement block executes, executes the statement in the finally statement block, and finally executes the statement after the last statement block;

Illustrates the execution of a try, catch, finally statement block:

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.