Java 简明教程

Java - Throws and Throw | Throw an Exception

Java throws and throw

如果一个 method 并未处理已检查的 exception ,则该方法必须使用 throws 关键字对其进行声明。throws 关键字出现在一个方法签名的末尾。

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature.

你可以使用 throw 关键字抛出一个异常,它既可以是一个新实例化的异常,也可以是你刚捕获的异常。

You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.

尝试理解 throws 和 throw 关键字之间的差异,throws 用于推迟对已检查异常的处理,而 throw 用于显式地调用一个异常。

Try to understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly.

Syntax

以下是使用 throws 和 throw 抛出异常的语法:

Following is the syntax of throwing an exception using throws and throw -

method(parameters) throws exception {
  // Method implementation
  throw new exception();
}

以下方法声明它抛出一个 RemoteException −

The following method declares that it throws a RemoteException −

考虑下面的示例代码以使用 throws 和 throw 关键字:

Consider the below example code to use throws and throw keywords -

import java.io.*;
public class className {

   public void deposit(double amount) throws RemoteException {
      // Method implementation
      throw new RemoteException();
   }
   // Remainder of class definition
}

一个方法可以声明它抛出多个异常,在这种情况下,异常被声明在一个以逗号分隔的列表中。例如,以下方法声明它抛出 RemoteException 和 InsufficientFundsException −

A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException −

import java.io.*;
public class className {

   public void withdraw(double amount) throws RemoteException,
      InsufficientFundsException {
      // Method implementation
   }
   // Remainder of class definition
}

Java Throws and Throw Example

以下示例显示了使用 throw 关键字在传递无效参数的情况下发送异常。我们正在调用一个 divide 方法,该方法检查第二个参数是否为零,然后会抛出一个带有自定义消息的 IllegalArgumentException。由于 IllegalArgumentException 是一个未经检查的异常,因此不需要 divide 方法来声明 throws 语句。现在,由于父方法没有处理异常,JVM 截获了该异常,并打印错误消息并终止程序。

Following example shows the use of throw keyword to send an exception in case a invalid argument is passed. We’re calling a divide method which checks if second parameter is zero then it will throw an IllegalArgumentException with a custom message. As IllegalArgumentException is an unchecked exception, the divide method is not required to declares throws statement. Now as parent method is not handling the exception, JVM intercepts the same and prints the error message and terminates the program.

package com.tutorialspoint;

public class ExcepTest {

   public static void main(String args[]) {
      int a = 3;
      int b = 0;
      System.out.println("result:" + divide(a,b));
   }

   private static int divide(int a, int b) {
      if(b == 0) {
         throw new IllegalArgumentException("second argument cannot be zero.");
      }
      return a / b;
   }
}
Exception in thread "main" java.lang.IllegalArgumentException: second argument cannot be zero.
   at com.tutorialspoint.ExcepTest.divide(ExcepTest.java:13)
   at com.tutorialspoint.ExcepTest.main(ExcepTest.java:8)

More Examples

Example 1: Throw an exception on invalid arguments

以下示例展示了使用 throw 和 throws 关键字在传入无效参数时发送异常并处理异常。我们调用一个 divide 方法,它检查第二个参数是否是零,如果是,则会抛出一个带有自定义消息的异常。由于异常是一个 checked 异常,divide 方法需要声明 throws 语句。现在,由于父方法要处理异常或声明 throws 异常,我们处理异常并打印消息。

Following example shows the use of throw and throws keywords to send an exception in case a invalid argument is passed and handle the exception. We’re calling a divide method which checks if second parameter is zero then it will throw an Exception with a custom message. As Exception is a checked exception, the divide method is required to declares throws statement. Now as parent method is to either handle the exception or declares the throws exception, we’re handling the exception and printing the message.

package com.tutorialspoint;

public class ExcepTest {

   public static void main(String args[]) {
      int a = 3;
      int b = 0;
      try {
         System.out.println("result:" + divide(a,b));
      } catch (Exception e) {
         System.out.println("Exception: " + e);
      }
   }

   private static int divide(int a, int b) throws Exception {
      if(b == 0) {
         throw new Exception("second argument cannot be zero.");
      }
      return a / b;
   }
}
Exception: java.lang.Exception: second argument cannot be zero.

Example 2: Using throws and throw in main and other method

以下示例展示了使用 throw 和 throws 关键字在传入无效参数时发送异常但不处理异常的用法。我们调用一个 divide 方法,它检查第二个参数是否是零,如果是,则会抛出一个带有自定义消息的异常。由于异常是一个 checked 异常,divide 方法需要声明 throws 语句。现在,由于父方法要处理异常或声明 throws 异常,我们声明抛出异常,然后 JVM 将处理异常。

Following example shows the use of throw and throws keywords to send an exception in case a invalid argument is passed and exception is not handled. We’re calling a divide method which checks if second parameter is zero then it will throw an Exception with a custom message. As Exception is a checked exception, the divide method is required to declares throws statement. Now as parent method is to either handle the exception or declares the throws exception, we’re declaring to throw the exception and JVM will handle the exception.

package com.tutorialspoint;

public class ExcepTest {

   public static void main(String args[]) throws Exception {
      int a = 3;
      int b = 0;
      System.out.println("result:" + divide(a,b));
   }

   private static int divide(int a, int b) throws Exception {
      if(b == 0) {
         throw new Exception("second argument cannot be zero.");
      }
      return a / b;
   }
}
Exception in thread "main" java.lang.Exception: second argument cannot be zero.
   at com.tutorialspoint.ExcepTest.divide(ExcepTest.java:15)
   at com.tutorialspoint.ExcepTest.main(ExcepTest.java:9)