【问题标题】:Java, Catching an exception and passing it to a methodJava,捕获异常并将其传递给方法
【发布时间】:2015-11-24 19:46:53
【问题描述】:

我创建了一个接受 IOException 作为参数的方法。此方法打开输出流并将有关异常的信息打印到文本文件中。我似乎遇到的问题.. 如何从 catch 块调用该方法?

try{
    if(true)
        throw new IOException();
}
catch(IOException e){
    //pass it to a method
}

:::编辑:::

public void logErrors(IOException e){
    PrintWriter out = yada yada;

    out.println(e.getCause());
}

【问题讨论】:

  • 就是yourMethod(e);
  • 调用你想要的方法(e);
  • 如果你得到一个 IOException,你可能不应该在捕获它之后尝试使用输出流,因为这可能是导致错误的原因。
  • 为什么要这样做?为什么要捕获与您在这段短代码中抛出的相同异常?为什么不干脆做:if (...) { myMethod(); } 并排除异常?
  • @Leah,我试过了......它说“未报告的异常......必须抛出或捕获”

标签: java methods exception-handling io


【解决方案1】:

基本上你只需要调用方法的名称,你希望方法的代码像这样执行:

try{
    if(true)
        throw new IOException();
}
catch(IOException e){
    //pass it to a method
    methodToExecute(e);
}

also, I can see that you throw an IOException in both cases so perhaps 
you may want to consider modifying the code to use a finally block

编辑

再想一想,您可以只使用 if 语句来始终抛出它。

if (...)
{
   yourMethod(throw new IOException());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多