在方法中分配throws子句

时间:2017-10-23 03:39:22

标签: java exception main

如何使用main方法签名中的throws子句来处理异常,如下例所示?

import java.io.File;
import java.io.IOException;

public class Exception {

    public static void main(String ... args) throws IOException {
        ioExceptionTest();
    }

    public static void ioExceptionTest() throws IOException {
        File file = new File("C:\\Users\\User\\Desktop\\Test.txt");

        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }
}

对我而言,它没有意义。

1 个答案:

答案 0 :(得分:1)

如果方法使用throws子句作为方法签名,则该方法中引发的任何异常都将被引发到调用该方法的调用者。调用者可以选择使用try catch块来处理异常,也可以使用throws子句将异常引发给任何调用它的人。

main方法的throws子句意味着异常将被引发到Java Virtual Machine,它将处理异常并打印堆栈跟踪。

class Example {
    // handle exception with a try catch block
    public static void main(String ... args) {
        try {
            myMethod();
        } catch (Exception e) {
            // handle the exception
        }
    }

    // raise exception to the Java Virtual Machine
    public static void main(String ... args) throws Exception {
            myMethod();
    }

    static void myMethod() throws Exception {
        // do something which may throw an Exception, such as
        throw new Exception("Meaningful description");
    }
}