在java中一次捕获多个异常?
在上面的代码中,在java中一次捕获多个异常?,java,exception,Java,Exception,在上面的代码中,NumberFormatException从catch块抛出,它将成功编译并运行,但当从catch块抛出FileNotFoundException时,它将不会编译。将引发以下错误: import java.io.*; class West1 extends Exception { private String msg; public West1() { } public West1(String msg) { super(msg
NumberFormatException
从catch块抛出,它将成功编译并运行,但当从catch块抛出FileNotFoundException
时,它将不会编译。将引发以下错误:
import java.io.*;
class West1 extends Exception {
private String msg;
public West1() {
}
public West1(String msg) {
super(msg);
this.msg=msg;
}
public West1(Throwable cause) {
super(cause);
}
public West1(String msg,Throwable cause) {
super(msg,cause);
this.msg=msg;
}
public String toString() {
return msg;
}
public String getMessage() {
return msg;
}
}
public class West {
public static void main(String[] args) {
try {
throw new West1("Custom Exception.....");
}catch(West1 ce) {
System.out.println(ce.getMessage());
//throw new NumberFormatException();
throw new FileNotFoundException();
}catch(FileNotFoundException fne) {
fne.printStackTrace();
}/*catch(NumberFormatException nfe) {
nfe.printStackTrace();
}*/
}
}
所以我的问题是,这种行为背后的原因是什么?NumberFormatException是一个RuntimeException,这意味着不需要在所有抛出它的方法中声明它。这意味着,与FileNotFoundException不同,编译器无法知道它是否可以被抛出到块中。标题意味着您试图同时捕获多个异常,您的代码意味着您了解,对于单个
try
block tocatch
不同类型的异常,您可以有多个catch
块。到目前为止,一切都很好,但您似乎误解了try
-catch
捕获错误的确切位置
这是你的密码。我删除了这些评论,使其更加简洁
West.java:40: error: exception FileNotFoundException is never thrown in body of
corresponding try statement
}catch(FileNotFoundException fne){
West.java:39: error: unreported exception FileNotFoundException; must be caught
or declared to be thrown
throw new FileNotFoundException();
试试看。请注意如何使用
try
而不是catch
。如果FileNotFoundException
不是一个异常,这无关紧要。看看检查与未检查的解释:消息是怎么说的。如果要让方法的throws
子句“escape”,则必须将FileNotFoundException添加到该子句中。请解释为什么在这样做时拒绝投票。我觉得我的答案很好地回答了OP的问题,但仍将进行编辑以更加清晰。
public class West {
public static void main(String[] args) {
try {
throw new West1("Custom Exception.....");
} catch(West1 ce) {
System.out.println(ce.getMessage());
throw new FileNotFoundException(); // <-- Must be caught
} catch(FileNotFoundException fne) { // <-- Never thrown
fne.printStackTrace();
}
}
}
public class West {
public static void main(String[] args) {
try {
throw new West1("Custom Exception.....");
} catch(West1 ce) {
System.out.println(ce.getMessage());
try {
throw new FileNotFoundException();
} catch(FileNotFoundException fne) {
fne.printStackTrace();
}
}
}
}