【问题标题】:How can I throw different kind of excptions in one method如何在一种方法中抛出不同类型的异常
【发布时间】:2021-08-10 13:31:32
【问题描述】:

我刚开始学习 Java,但我被困住了。我被告知要处理对方法的调用,在 main 方法中可以抛出不同类型的异常。

抛出什么:IOException 如何处理:在 IllegalArgumentException 中包裹一条消息“资源错误”并抛出它

抛出什么:FileNotFoundException 如何处理:在 IllegalArgumentException 中包裹一条消息“Resource is missing”并抛出它:

这是一个起点,即给出:

static Exception exception = new FileNotFoundException();

public static void main(String[] args) throws Exception {
  riskyMethod();
}

public static void riskyMethod() throws Exception {
  throw exception;
}

【问题讨论】:

标签: java exception throw


【解决方案1】:

要处理riskyMethod() 可以抛出的异常,请将其放入try-catch 块中。您可以在try 之后放置几个catch 块来处理不同的异常。要将任何异常包装到 IllegalArgumentException 中,请将异常作为第二个参数传递给构造函数。第一个参数是错误字符串。 整个代码:

static Exception exception = new FileNotFoundException();

public static void main(String[] args) throws Exception {
    try{
        riskyMethod();
    }catch(FileNotFoundException e){
        throw new IllegalArgumentException("Resource is missing", e);
    }catch(IOException e){
        throw new IllegalArgumentException("Resource error", e);
    }
}

public static void riskyMethod() throws Exception {
   throw exception;
}

我没有测试这段代码,但是在添加必要的导入之后它应该可以工作。

【讨论】:

  • 非常感谢!
  • 这个答案到底添加了什么?直接抛出原始异常不是更好吗?
【解决方案2】:

首先,从您的 main 中删除 throws Exception

处理一个异常意味着不重新抛出它,或者抛出一个不同的。

捕获异常并对其进行处理:

public static void main(String[] args) {
    try {
        riskyMethod();
    } catch (IOException e) {
        System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
    }
}

你可以打印你喜欢的 - 这只是一个建议。

请注意,您不需要专门捕获FileNotFoundException,因为它是一个IOException

【讨论】:

    猜你喜欢
    • 2015-12-17
    • 2020-11-10
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 2023-03-20
    相关资源
    最近更新 更多