【问题标题】:how to throw an IOException?如何抛出 IOException?
【发布时间】:2012-03-31 23:26:12
【问题描述】:
public class ThrowException {
    public static void main(String[] args) {
        try {
            foo();
        }
        catch(Exception e) {
             if (e instanceof IOException) {
                 System.out.println("Completed!");
             }
          }
    }
    static void foo() {
        // what should I write here to get an exception?
    }
}

嗨!我刚开始学习异常并且需要赶上一个expetion,所以请任何人都可以为我提供解决方案吗? 我将不胜感激。 谢谢!

【问题讨论】:

  • 什么是foo,它与a有什么关系?
  • 这只是基本的 Java 语法,任何书籍或 Java 介绍都会教你。我建议阅读一些。

标签: java exception io


【解决方案1】:
static void foo() throws IOException {
    throw new IOException("your message");
}

【讨论】:

  • 我应该在 foo 方法中写这个吗?
  • 是的。如果到达此行,将引发异常。
  • 请注意,必须声明 foo 方法才能抛出异常。否则你会得到一个编译器错误
  • 哦 - 我忘了。感谢您的提示!我更新了答案。
【解决方案2】:
try {
        throw new IOException();
    } catch(IOException e) {
         System.out.println("Completed!");
    }

【讨论】:

    【解决方案3】:

    刚开始学习异常,需要捕捉异常

    抛出异常

    throw new IOException("Something happened")
    

    要捕获此异常最好不要使用Exception,因为它非常通用,而是要捕获您知道如何处理的特定异常:

    try {
      //code that can generate exception...
    }catch( IOException io ) {
      // I know how to handle this...
    }
    

    【讨论】:

      【解决方案4】:

      如果目标是从foo()方法抛出异常,则需要声明如下:

      public void foo() throws IOException{
          //do stuff
          throw new IOException("message");
      }
      

      然后在你的主要:

      public static void main(String[] args){
          try{
              foo();
          } catch (IOException e){
              System.out.println("Completed!");
          }
      }
      

      请注意,除非 foo 被声明为抛出 IOException,否则尝试捕获一个将导致编译器错误。使用catch (Exception e)instanceof 对其进行编码将防止编译器错误,但这是不必要的。

      【讨论】:

        【解决方案5】:
        throw new IOException("Test");
        

        【讨论】:

          【解决方案6】:

          请尝试以下代码:

          throw new IOException("Message");
          

          【讨论】:

            【解决方案7】:

            也许这会有所帮助...

            请注意以下示例中捕获异常的更简洁的方法 - 您不需要 e instanceof IOException

            public static void foo() throws IOException {
                // some code here, when something goes wrong, you might do:
                throw new IOException("error message");
            }
            
            public static void main(String[] args) {
                try {
                    foo();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
            

            【讨论】:

              猜你喜欢
              • 2012-06-14
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-06-28
              • 2015-07-26
              相关资源
              最近更新 更多