Is the above considered to be a checked exception?
No
The fact that you are handling an exception does not make it a Checked Exception
if it is a RuntimeException
.
Is RuntimeException
an unchecked exception
?
Yes
Checked Exceptions
are subclasses
of java.lang.Exception
Unchecked Exceptions
are subclasses
of java.lang.RuntimeException
抛出已检查异常的调用需要包含在try{}块中,或者在方法调用方的上级级别中进行处理。在这种情况下,当前方法必须声明它抛出所述异常,以便调用方可以做出适当的安排来处理异常。
希望这能有所帮助。
Q: should I bubble up the exact
exception or mask it using Exception?
A: 是的,这是一个非常好的问题,也是重要的设计考虑因素。类Exception是一个非常通用的异常类,可用于包装内部低级别异常。你最好创建一个自定义的异常并将其包裹起来。但是,还有一个大的异常——永远不要混淆潜在的原始根本原因。例如,永远不要
执行以下操作-
try {
attemptLogin(userCredentials);
} catch (SQLException sqle) {
throw new LoginFailureException("Cannot login!!"); //<-- Eat away original root cause, thus obscuring underlying problem.
}
相反,请执行以下操作:
try {
attemptLogin(userCredentials);
} catch (SQLException sqle) {
throw new LoginFailureException(sqle); //<-- Wrap original exception to pass on root cause upstairs!.
}
Eating away original root cause buries the actual cause beyond recovery is a nightmare for production support teams where all they are given access to is application logs and error messages.
Although the latter is a better design but many people don t use it often because developers just fail to pass on the underlying message to caller. So make a firm note: Always pass on the actual exception
back whether or not wrapped in any application specific exception.
在尝试捕获RuntimeExceptions
时
RuntimeException
作为一般规则,不应尝试捕获。它们通常是编程错误的信号,应该单独处理。相反,程序员应该在调用一些可能导致<code>RuntimeException</code>的代码之前检查错误条件。例如:
try {
setStatusMessage("Hello Mr. " + userObject.getName() + ", Welcome to my site!);
} catch (NullPointerException npe) {
sendError("Sorry, your userObject was null. Please contact customer care.");
}
这是一种糟糕的编程实践。相反,应该像这样进行空检查-
if (userObject != null) {
setStatusMessage("Hello Mr. " + userObject.getName() + ", Welome to my site!);
} else {
sendError("Sorry, your userObject was null. Please contact customer care.");
}
但有时这种错误检查是昂贵的,比如数字格式,考虑一下-
try {
String userAge = (String)request.getParameter("age");
userObject.setAge(Integer.parseInt(strUserAge));
} catch (NumberFormatException npe) {
sendError("Sorry, Age is supposed to be an Integer. Please try again.");
}
在这里,调用前的错误检查是不值得的,因为它本质上意味着在parseInt()方法中复制所有字符串到整数的转换代码,并且如果由开发人员实现,则很容易出错。所以最好不要尝试接球。
因此,NullPointerException
和NumberFormatException
RuntimeExceptions,捕获NullPointerException
应该替换为优雅的null检查,而我建议显式捕获NumberFormatException
,以避免可能引入容易出错的代码。