1

我们可以在同一个方法中使用throwstry-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 语句,如果没有告诉我添加的适当位置?

4

1 回答 1

2

在您的代码中

 void t() throws IllegalAccessException

您是在告诉编译器此代码抛出异常(是否抛出是另一回事),因此任何调用此方法的方法都必须捕获它或声明它抛出它等等。

由于您实际上并没有引发异常,t因此您可以删除声明。

void t()
于 2021-06-07T06:49:17.070 回答