Java初学者疑惑:空指针异常处理实例
在Java中,空指针异常(NullPointerException)是由于尝试访问一个null对象的属性或方法而引起的。
以下是一个简单的异常处理实例,当试图访问null字符串时,程序会捕获这个异常并给出提示:
public class NullPointerExample {
public static void main(String[] args) {
// 创建null引用
String nullStr = null;
try {
// 访问null对象的属性
System.out.println(nullStr.length()); // 这会抛出NullPointerException
} catch (NullPointerException npe) {
// 捕获异常并处理
System.out.println("Error: Null Pointer Exception. Check if the object is null or not." + npe.getMessage());
}
}
}
在这个例子中,我们首先创建了一个null引用的字符串。然后尝试访问这个null对象的长度属性,这自然会抛出一个NullPointerException。
最后,我们在try-catch块中捕获了这个异常,并打印了一条包含错误信息和异常堆栈跟踪的消息。
还没有评论,来说两句吧...