有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何抛出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?
    }
}

嗨!我刚刚开始了解异常情况,需要了解一个问题,所以有谁能给我提供一个解决方案吗? 我将非常感激。 谢谢


共 (4) 个答案

  1. # 1 楼答案

    请尝试以下代码:

    throw new IOException("Message");
    
  2. # 2 楼答案

    static void foo() throws IOException {
        throw new IOException("your message");
    }
    
  3. # 3 楼答案

    try {
            throw new IOException();
        } catch(IOException e) {
             System.out.println("Completed!");
        }
    
  4. # 4 楼答案

    I just started learning exceptions and need to catch an exception

    抛出异常

    throw new IOException("Something happened")
    

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

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