[英]Usage of throws and try-catch in the same method
我们可以用同样的方法使用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语句,并且 rest 是相同的。
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");
}
}
但现在我得到了想要的 output。 但我有一些问题...
在您的代码中
void t() throws IllegalAccessException
您是在告诉编译器此代码抛出异常(是否抛出是另一回事),因此任何调用此方法的方法都必须捕获它或声明它也抛出它等等。
由于您实际上并没有从t
抛出异常,因此您可以删除声明。
void t()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.