How to handle exceptions thrown in Java?
In Java, you can use a try-catch block to catch and handle exceptions thrown by a throw statement. The code in the try block wraps the code that may throw an exception, while the catch block is used to catch and handle the thrown exception.
Can you please provide me with an example?
public class Example {
public static void main(String[] args) {
try {
// 可能会抛出异常的代码
throwException();
} catch (Exception e) {
// 捕获并处理抛出的异常
System.out.println("捕获到异常:" + e.getMessage());
}
}
public static void throwException() throws Exception {
// 抛出异常
throw new Exception("这是一个异常");
}
}
In the example above, the throwException() method throws an Exception, which is then caught and handled in the main method using a try-catch block. If there is no try-catch block to catch the exception, the program will terminate and print the stack trace of the exception.
When using the throw statement to throw an exception, it is necessary to declare the exception in the method signature. In the example above, the signature of the throwException() method is “throws Exception,” indicating that this method may throw an Exception.