我们可以在同一个方法中使用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");
}
}
但现在我得到了想要的输出。 但我有一些问题...