【发布时间】:2021-08-24 06:22:54
【问题描述】:
我们可以在同一方法中使用 throws 和 try-catch 吗?
public class Main
{
static void t() throws IllegalAccessException {
try{
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
System.out.println(e);
}
}
public static void main(String[] args){
t();
System.out.println("hello");
}
}
显示的错误是
Main.java:21: error: unreported exception IllegalAccessException; must be caught or declared to be thrown
t();
^
1 error
所以我想到了修改代码,并在 main() 方法中添加了另一个 throws 语句,其余相同。
public class Main
{static void t() throws IllegalAccessException {
try{
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
System.out.println(e);
}
}
public static void main(String[] args) throws IllegalAccessException{
t();
System.out.println("hello");
}
}
但现在我得到了想要的输出。 但我有一些问题......
我们可以在单一方法中使用 throws 和 try-catch 吗?
在我的情况下是否需要添加两个 throws 语句,如果没有告诉我添加的适当位置?
【问题讨论】:
-
是的,你可以,一个常见的用法是抛出一个
IllegalStateException并使用tryCatch 来使用另一种类型的异常,比如NullPointerException,或者使用tryCatch 来捕获一个用户无能为力的异常使用,例如初始化java.awt.Robot的实例。 -
不,你不需要任何
throws语句,因为实际上没有从任何方法中抛出检查异常。
标签: java exception try-catch throws illegalaccessexception