如果方法抛出未在方法声明中使用"throws"指定的异常,会发生什么情况

blu*_*llu 20 java exception throws

我从来没有使用过"throws"子句,今天一个配偶告诉我,我必须在方法声明中指定方法可能抛出的异常.但是,如果不这样做,我一直在使用异常而没有问题,所以,如果事实上它需要它,为什么还需要呢?

And*_*s_D 24

Java有两种不同类型的异常:checked Exceptions和unchecked Exceptions.

未经检查的异常是子类,RuntimeException您不必添加throws声明.所有其他异常必须在方法体中处理,可以使用try/catch语句或使用throws声明.

未经检查的异常的示例:IllegalArgumentException有时用于通知,已使用非法参数调用方法.不需要投掷.

已检查异常的示例:包IOException中的某些方法java.io可能会抛出.使用try/catch或添加throws IOException到方法声明并将异常处理委托给方法调用者.


Ant*_*ton 13

如果使用throws关键字声明了一个方法,那么任何其他希望调用该方法的方法都必须准备好捕获它或声明它本身会引发异常.

例如,如果要暂停应用程序,则必须调用 Thread.sleep(milliseconds);

但是这种方法的声明说它会抛出一个 InterruptedException

宣言:

public static void sleep(long millis) throws InterruptedException
Run Code Online (Sandbox Code Playgroud)

因此,如果您希望在main方法中调用它,则必须捕获它:

public static void main(String args[]) {
    try {
        Thread.sleep(1000);
    } catch(InterruptedException ie) {
        System.out.println("Opps!");
    }
}
Run Code Online (Sandbox Code Playgroud)

或者让方法也声明它抛出异常:

public static void main(String args[]) throws InterruptedException {
    Thread.sleep(1000);
}
Run Code Online (Sandbox Code Playgroud)


fin*_*nnw 6

即使有经过检查的例外,它也可能发生.有时它会打破记录.

假设一个库方法使用这个技巧来允许实现Runnable可以抛出IOException:

class SneakyThrowTask implements Runnable {

    public void run() {
        throwSneakily(new IOException());
    }

    private static RuntimeException throwSneakily(Throwable ex) {
        return unsafeCastAndRethrow(ex);
    }

    @SuppressWarnings("unchecked")
    private static <X extends Throwable>X unsafeCastAndRethrow(Throwable ex) throws X {
        throw (X) ex;
    }

}
Run Code Online (Sandbox Code Playgroud)

你这样称呼它:

public static void main(String[] args) {
    try {
        new SneakyThrowTask().run();
    } catch (RuntimeException ex) {
        LOGGER.log(ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

永远不会记录该异常.因为它是一个经过检查的例外,你不能这样写:

public static void main(String[] args) {
    try {
        new SneakyThrowTask().run();
    } catch (RuntimeException ex) {
        LOGGER.log(ex);
    } catch (IOException ex) {
        LOGGER.log(ex); // Error: unreachable code
    }
}
Run Code Online (Sandbox Code Playgroud)