在同一方法中使用 throws 和 try-catch 我们可以在单个方法中使用 throws 和 try-catch 吗?在我的情况下是否需要添加两个throws语句,如果没有告诉我添加的适当位置?

问题描述

我们可以在相同的方法中使用 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

于是我想到了修改代码,在ma​​in()方法添加了另一个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语句,如果没有告诉我添加的适当位置?

解决方法

在你的代码中

 void t() throws IllegalAccessException

你告诉编译器这个代码抛出一个异常(不管它是否抛出是另一回事),所以任何调用这个方法的方法要么必须捕获它,要么声明它抛出它等等等等

由于您实际上并未从 t 抛出异常,因此您可以删除声明。

void t()