像这样处理空指针异常是否有意义
private void doWork(Object object) {
if (object == null) {
try {
throw new IllegalArgumentException();
} catch (Exception e) {
e.printStackTrace();
}
} else {
...
}
}
最佳答案
不,那真的没有意义。
不要捕获异常。就这样
if (object == null)
throw new IllegalArgumentException("Argument object may not equal null");
根据您的建议,该方法将记录为
Do some work given argument
object
. Ifobject
isnull
it prints some garbage on standard out and does nothing else.
作为旁注,由于您仍在学习 Java,因此您的 try-catch block :
try {
throw new IllegalArgumentException();
} catch (Exception e) {
e.printStackTrace();
}
...等同于...
new IllegalArgumentException().printStackTrace();
关于java - 这样处理空指针异常有意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7145240/