Java 简明教程

Java Try Catch Block

exception (或异常事件) 是在程序执行过程中出现的问题。当发生 Exception 时,程序的正常流程会遭到破坏,并且程序/应用程序会异常终止,这种情况并不可取,因此,这些异常应得到处理。

An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.

Java try and catch

使用 trycatch 关键字的组合可以捕获异常。一个 try 和 catch 块放在可能生成异常的代码周围。try 和 catch 块中的代码被称为受保护代码,并且使用 try/catch 的语法如下所示:

A method catches an exception using a combination of the try and catch keywords. A try and catch block is placed around the code that might generate an exception. Code within a try and catch block is referred to as protected code, and the syntax for using try/catch looks like the following −

The try Block

容易产生异常的代码被放置在 try 块中。当异常发生时,该发生的异常由与它关联的 catch 块处理。每个 try 块应该紧接着一个 catch 块或 finally 块。

The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block.

The catch Block

catch 语句涉及声明你试图捕获的异常类型。如果受保护代码中发生异常,则检查 try 之后的 catch 块(或块)。如果发生的异常类型被列在一个 catch 块中,则异常被传递到 catch 块中,就像一个参数被传递到一个方法参数中一样。

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

Syntax of Java try and catch Block

try {
   // Protected code
} catch (ExceptionName e1) {
   // Catch block
}

Example of Java try and catch Block

在以下示例中,声明了一个包含 2 个元素的数组。然后,代码尝试访问数组的第 3 个元素,它会引发一个异常。由于我们已用一个 try 块将代码包围起来,因此可以在下一个 catch 块中处理此异常,我们已声明该 catch 块来捕获 ArrayIndexOutOfBoundsException。在捕获异常之后,我们可以执行相应的操作。此处,我们在打印所引发异常的详细信息。

In following example, an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception. As we’ve enclosed the code with a try block, this exception can be handled within next catch block which we’ve declared to catch ArrayIndexOutOfBoundsException. After catching the exception, we can take the corresponding action. Here we’re printing the details of the exception thrown.

package com.tutorialspoint;

public class ExcepTest {

   public static void main(String args[]) {
      try {
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
}
Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple Catch Blocks With Java Try

一个 try 块可以跟随多个 catch 块。多个 catch 块的语法如下所示 −

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following −

Syntax: Multiple Catch Blocks

try {
   // Protected code
} catch (ExceptionType1 e1) {
   // Catch block
} catch (ExceptionType2 e2) {
   // Catch block
} catch (ExceptionType3 e3) {
   // Catch block
}

前面的语句演示了三个 catch 块,但是你可以在一个 try 之后可以有任意数量的 catch 块。如果受保护代码中发生异常,则异常被抛到列表中的第一个 catch 块。如果抛出的异常的数据类型匹配 ExceptionType1,则异常在该处被捕获。如果没有,则异常传递到第二个 catch 语句。这将持续到异常被捕获或者通过所有 catch,在这种情况下,当前方法停止执行并且异常被抛到调用堆栈上先前的那个方法。

The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.

Example: Multiple Catch Blocks

此处是如何使用多个 try/catch 语句的代码片段。在此示例中,我们正在通过将一个值除以 0 来创建一个错误。由于该错误并不是一个 ArrayIndexOutOfBoundsException,所以下一个 catch 块处理该异常并打印该详细信息。

Here is code segment showing how to use multiple try/catch statements. In this example, we’re creating an error by dividing a value by 0. As it is not an ArrayIndexOutOfBoundsException, next catch block handles the exception and prints the details.

package com.tutorialspoint;

public class ExcepTest {

   public static void main(String args[]) {
      try {
         int a[] = new int[2];
         int b = 0;
         int c = 1/b;
         System.out.println("Access element three :" + a[3]);
      }
      catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("ArrayIndexOutOfBoundsException thrown  :" + e);
      }catch (Exception e) {
          System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
}
Exception thrown  :java.lang.ArithmeticException: / by zero
Out of the block

Catching Multiple Exceptions with Java Try and Catch Block

自 Java 7 起,你可以使用一个 catch 块处理多个异常,这个功能简化了代码。以下是处理它的方法 −

Since Java 7, you can handle more than one exception using a single catch block, this feature simplifies the code. Here is how you would do it −

Syntax: Catching Multiple Exceptions

catch (IOException|FileNotFoundException ex) {
   logger.log(ex);
   throw ex;

Example: Catching Multiple Exceptions

以下代码片段展示了如何在单一语句中使用多个 catch。在这个例子中,我们通过将一个值除以 0 来创建一个错误。在单一语句中,我们处理 ArrayIndexOutOfBoundsException 和 ArithmeticException。

Here is code segment showing how to use multiple catch in a single statement. In this example, we’re creating an error by dividing a value by 0. In single statement, we’re handling ArrayIndexOutOfBoundsException and ArithmeticException.

package com.tutorialspoint;

public class ExcepTest {

   public static void main(String args[]) {
      try {
         int a[] = new int[2];
         int b = 0;
         int c = 1/b;
         System.out.println("Access element three :" + a[3]);
      }
      catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
         System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
}
Exception thrown  :java.lang.ArithmeticException: / by zero
Out of the block