我想知道为什么当方法永远不会抛出异常时,java编译器允许在方法声明中抛出异常。因为“抛出”是一种处理异常的方式(告诉调用者处理它)。
因为有两种处理异常的方法(抛出和尝试/捕获)。在 try/catch 中,它不允许捕获未在 try 块中抛出的异常,但它允许在可能不会抛出异常的方法中抛出异常。
private static void methodA() {
try {
// Do something
// No IO operation here
} catch (IOException ex) { //This line does not compile because
//exception is never thrown from try
// Handle
}
}
private static void methodB() throws IOException { //Why does this //compile when excetion is never thrown in function body
//Do Something
//No IO operation
}