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

你好! 我剛開始學習異常,需要抓住一個expetion,所以請誰能給我一個解決方案? 我會很感激。 謝謝!

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

我剛開始學習異常,需要捕捉異常

拋出異常

throw new IOException("Something happened")

要捕獲此異常,最好不要使用Exception因為它太通用了,而是要捕獲您知道如何處理的特定異常:

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

如果目標是從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對其進行編碼將防止編譯器錯誤,但這是不必要的。

請嘗試以下代碼:

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

也許這有助於...

請注意以下示例中捕獲異常的更清晰的方法 - 您不需要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