简体   繁体   English

如何抛出 IOException?

[英]how to throw an IOException?

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?
    }
}

Hi!你好! I just started learning exceptions and need to catch an expetion, so please can anybody provide me with a solution?我刚开始学习异常,需要抓住一个expetion,所以请谁能给我一个解决方案? I'd be very grateful.我会很感激。 Thanks!谢谢!

static void foo() throws IOException {
    throw new IOException("your message");
}
try {
        throw new IOException();
    } catch(IOException e) {
         System.out.println("Completed!");
    }

I just started learning exceptions and need to catch an exception我刚开始学习异常,需要捕捉异常

To throw an exception抛出异常

throw new IOException("Something happened")

To catch this exception is better not use Exception because is to much generic, instead, catch the specific exception that you know how to handle:要捕获此异常,最好不要使用Exception因为它太通用了,而是要捕获您知道如何处理的特定异常:

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

If the goal is to throw the exception from the foo() method, you need to declare it as follows:如果目标是从foo()方法抛出异常,则需要如下声明:

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

Then in your main:然后在你的主要:

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

Note that, unless foo is declared to throw an IOException, attempting to catch one will result in a compiler error.请注意,除非 foo 被声明为抛出 IOException,否则尝试捕获一个将导致编译器错误。 Coding it using a catch (Exception e) and an instanceof will prevent the compiler error, but is unnecessary.使用catch (Exception e)instanceof对其进行编码将防止编译器错误,但这是不必要的。

请尝试以下代码:

throw new IOException("Message");
throw new IOException("Test");

Maybe this helps...也许这有助于...

Note the cleaner way to catch exceptions in the example below - you don't need the e instanceof IOException .请注意以下示例中捕获异常的更清晰的方法 - 您不需要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());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM