繁体   English   中英

throws 和 try-catch 的用法相同

[英]Usage of throws and try-catch in the same method

我们可以用同样的方法使用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语句,并且 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。 但我有一些问题...

我们可以在单一方法中使用 throws 和 try-catch 吗?

在我的情况下是否有必要添加两个 throws 语句,如果没有告诉我添加的适当位置?

在您的代码中

 void t() throws IllegalAccessException

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

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

void t()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM