【问题标题】:Usage of throws and try-catch in the same method在同一方法中使用 throws 和 try-catch
【发布时间】:2021-08-24 06:22:54
【问题描述】:

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

【问题讨论】:

  • 是的,你可以,一个常见的用法是抛出一个IllegalStateException 并使用tryCatch 来使用另一种类型的异常,比如NullPointerException,或者使用tryCatch 来捕获一个用户无能为力的异常使用,例如初始化java.awt.Robot 的实例。
  • 不,你不需要任何throws 语句,因为实际上没有从任何方法中抛出检查异常。

标签: java exception try-catch throws illegalaccessexception


【解决方案1】:

在你的代码中

 void t() throws IllegalAccessException

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

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

void t()

【讨论】:

  • 实际上我从 t() 方法抛出了一个异常。你能告诉我是否可以在同一方法中使用 throws 和 try-catch?
  • 不,你不是。你将它从try 块中扔出去,它被抓住了。不需要声明为 throwing 。
猜你喜欢
  • 2018-07-18
  • 2016-02-19
  • 1970-01-01
  • 2014-08-23
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 2012-10-18
相关资源
最近更新 更多