【发布时间】:2018-05-20 12:32:42
【问题描述】:
当我必须使用“throws”关键字时,我并不完全理解。考虑这段代码:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void otherMethod() throws InputMismatchException {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println(num);
}
public static void main (String[] args) {
try {
otherMethod();
} catch(InputMismatchException e) {
System.out.println("Please input an integer");
}
}
}
如果您输入的不是整数,则会导致 InputMismatchException。这个异常被传递给 main 方法。但是,我发现otherMethod()的“throws InputMismatchException”部分根本没有关系,没有它的main方法仍然可以正确处理异常。如果没有这部分,代码将如下所示:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void otherMethod() {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println(num);
}
public static void main (String[] args) {
try {
otherMethod();
} catch(InputMismatchException e) {
System.out.println("Please input an integer");
}
}
}
我想知道何时以及为何使用“throws”关键字,以及它的实际作用。
【问题讨论】:
-
至少相关,可能重复:stackoverflow.com/questions/4889711/…