How to use the “throws” keyword in Java?
In Java, the “throws” keyword is used in a method signature to declare possible exceptions that can be thrown, allowing the calling code to catch and handle the exception. If a method declares a “throws” clause for a possible exception but does not actually catch and handle it, then the exception will be propagated to the method that called it.
Here is an example of using the ‘throws’ keyword in Java to declare and handle exceptions.
// 声明一个方法可能抛出异常
public void method1() throws Exception {
// ...
}
// 在调用方法的代码中捕获和处理异常
public void method2() {
try {
method1();
} catch (Exception e) {
// 处理异常
}
}
// 在调用方法的代码中继续抛出异常
public void method3() throws Exception {
method1();
}
In the declaration of method1, use the throws keyword to specify the types of exceptions that may be thrown. In method2, we call method1 and catch and handle any potential exceptions using a try-catch block. In method3, we simply continue to throw the exception without handling it.
Please note that if a method declares a throws clause, the calling method must either catch and handle the exception or continue to throw it. Otherwise, the code will not compile.