我想知道为什么Java编译器允许在方法声明中使用throws,即使该方法永远不会抛出异常。因为"throws"是处理异常的一种方式(告诉调用者去处理它)。
由于处理异常有两种方式(throws和try/catch)。在try/catch中,它不允许捕获try块中未抛出的异常,但是它允许在可能不会抛出异常的方法中使用throws。
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
}