【问题标题】:When catch block statements will appear何时会出现 catch 块语句
【发布时间】:2014-12-20 05:33:53
【问题描述】:

作为一名学生,我正在编写 2 年的程序。我只是好奇什么时候会出现 catch 语句。我尽一切努力让我的程序输出 catch 块内的语句,但我失败了。有什么想法吗?

try{
    System.out.print("Enter a sentence: ");
      String sentence = dataIn.readLine();
      String res = sentence.replaceAll(" ", "");
    System.out.println(res);
  }catch(IOException e){
    e.printStackTrace();
    System.err.println(e);
  }
}

【问题讨论】:

    标签: java exception-handling error-handling


    【解决方案1】:

    你可以throw new IOException点赞

    try {
        throw new IOException("Like this");
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println(e);
    }
    

    输出是

    java.io.IOException: Like this
        at com.stackoverflow.Main.main(Main.java:8)
    java.io.IOException: Like this
    

    【讨论】:

    • 是否可以在没有“抛出新异常”的情况下显示里面的语句?
    • @Patrick 当然,但是必须抛出异常。如果您希望它始终运行,那么您需要一个 finally 块。
    • 哦,谢谢先生,我明白了。 finally 块总是在 try 块退出 -docs.oracle 时执行。谢谢你启发我。
    【解决方案2】:

    当里面的代码抛出IOException时触发

    您可以通过以下方式非常简单地强制它发生:

    try{
        System.out.print("Enter a sentence: ");
        String sentence = dataIn.readLine();
        String res = sentence.replaceAll(" ", "");
        System.out.println(res);
        throw new IOException("Testing");
    } catch(IOException e) {
        e.printStackTrace();
        System.err.println(e);
    }
    

    无论您的 dataIn 对象是什么,都可以抛出一个,例如,如果它正在读取的流出现错误

    【讨论】:

    • 触发 catch 块需要什么样的输入?
    • 可能与输入无关,而是来自流/网络/文件/计算机/等
    • 很好,先生,我现在很清楚异常处理是如何工作的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 2016-03-15
    相关资源
    最近更新 更多