Java异常处理与捕获案例解析
Java中的异常处理是通过try-catch-finally结构来实现的。以下是一个典型的异常处理和捕获案例:
public class ExceptionHandlingExample {
public static void main(String[] args) {
// 试图访问一个不存在的对象,这会抛出NullPointerException
try {
String str = new String();
System.out.println(str.length());
} catch (NullPointerException npe) {
// 捕获到NullPointerException
System.out.println("Caught a NullPointerException: " + npe.getMessage());
} finally {
// 始终会执行,无论是否抛出异常
System.out.println("This is the final block, always executed.");
}
}
}
在这个案例中,我们试图访问一个不存在的对象,这会抛出NullPointerException。通过try-catch-finally结构,我们可以捕获并处理这个异常,确保程序的正常运行。
还没有评论,来说两句吧...