约书亚·布洛赫在《有效的Java》中说过

为以下情况使用检查异常 可恢复条件和运行时 编程错误的例外 (第二版第58项)

看看我理解的对不对。

以下是我对受控异常的理解:

try{
    String userInput = //read in user input
    Long id = Long.parseLong(userInput);
}catch(NumberFormatException e){
    id = 0; //recover the situation by setting the id to 0
}

1. 上述异常是否被认为是受控异常?

2. RuntimeException是未检查的异常吗?

以下是我对未检查异常的理解:

try{
    File file = new File("my/file/path");
    FileInputStream fis = new FileInputStream(file);   
}catch(FileNotFoundException e){

//3. What should I do here?
    //Should I "throw new FileNotFoundException("File not found");"?
    //Should I log?
    //Or should I System.exit(0);?
}

4. 现在,上面的代码不能也是一个受控异常吗?我可以试着挽回这样的局面吗?我可以吗?(注:我的第三个问题在上面的陷阱里)

try{
    String filePath = //read in from user input file path
    File file = new File(filePath);
    FileInputStream fis = new FileInputStream(file);   
}catch(FileNotFoundException e){
    //Kindly prompt the user an error message
    //Somehow ask the user to re-enter the file path.
}

5. 人们为什么要这样做?

public void someMethod throws Exception{

}

为什么他们让异常冒出来?早点处理错误不是更好吗?为什么要冒出来?

6. 我是否应该冒泡出确切的异常或使用异常掩盖它?

以下是我的阅读资料

在Java中,什么时候应该创建检查异常,什么时候应该是运行时异常?

何时选择已检查异常和未检查异常


当前回答

上述异常是否被认为是受控异常? 没有 如果异常是RuntimeException,那么您正在处理的异常并不会使其成为Checked exception。 RuntimeException是未检查的异常吗? 是的

受控异常是java.lang.Exception的子类 未检查异常是java.lang.RuntimeException的子类

抛出已检查异常的调用需要包含在try{}块中,或者在方法调用方的更高级别中处理。在这种情况下,当前方法必须声明它抛出上述异常,以便调用者可以做出适当的安排来处理异常。

希望这能有所帮助。

问:我应该把确切的泡沫 异常或屏蔽它使用异常?

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!.
}

对生产支持团队来说,消除原始的根本原因,掩盖无法恢复的实际原因是一场噩梦,因为他们只能访问应用程序日志和错误消息。 虽然后者是一种更好的设计,但许多人不经常使用它,因为开发人员无法将底层消息传递给调用者。因此,请明确指出:无论是否封装在任何特定于应用程序的异常中,始终将实际异常传递回去。

在尝试捕获runtimeexception时

runtimeexception作为一般规则不应该被尝试捕获。它们通常是一个编程错误的信号,应该被置之不理。相反,程序员应该在调用一些可能导致RuntimeException的代码之前检查错误条件。为例:

try {
    setStatusMessage("Hello Mr. " + userObject.getName() + ", Welcome to my site!);
} catch (NullPointerException npe) {
   sendError("Sorry, your userObject was null. Please contact customer care.");
}

这是一种糟糕的编程实践。相反,null检查应该像-那样执行

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()方法中的所有字符串到整数转换代码——如果由开发人员实现,则很容易出错。因此,最好是取消try-catch。

因此NullPointerException和NumberFormatException都是runtimeexception,捕获一个NullPointerException应该替换为一个优雅的空检查,而我建议显式捕获NumberFormatException以避免可能引入容易出错的代码。

其他回答

关于未检查异常和已检查异常之间的区别,我最喜欢的描述来自Java教程的试用文章“未检查异常-争议”(很抱歉在这篇文章中介绍了所有基本的内容-但是,嘿,基本的有时是最好的):

这是底线原则:如果客户可以合理地 希望从异常中恢复,使其成为受控异常。如果 客户端不能做任何事情来从异常中恢复 未经检查的异常

“抛出哪种类型的异常”的核心是语义的(在某种程度上),上面的引用提供了一个很好的指导方针(因此,我仍然被c#摆脱受控异常的概念所震撼——特别是Liskov认为它们有用)。

接下来的问题就变得合乎逻辑了:编译器希望我显式地响应哪些异常?你希望客户能从中恢复过来。

Java distinguishes between two categories of exceptions (checked & unchecked). Java enforces a catch or declared requirement for checked exceptions. An exception's type determines whether an exception is checked or unchecked. All exception types that are direct or indirect subclasses of class RuntimeException are unchecked exception. All classes that inherit from class Exception but not RuntimeException are considered to be checked exceptions. Classes that inherit from class Error are considered to be unchecked. Compiler checks each method call and deceleration to determine whether the method throws checked exception. If so the compiler ensures the exception is caught or is declared in a throws clause. To satisfy the declare part of the catch-or-declare requirement, the method that generates the exception must provide a throws clause containing the checked-exception. Exception classes are defined to be checked when they are considered important enough to catch or declare.

为了回答最后一个问题(上面的其他问题似乎都得到了彻底的回答),“我应该冒泡出确切的异常还是使用exception掩盖它?”

我猜你的意思是这样的:

public void myMethod() throws Exception {
    // ... something that throws FileNotFoundException ...
}

不,总是声明尽可能精确的异常,或者一个这样的列表。你声明你的方法能够抛出的异常是你的方法和调用者之间契约的一部分。抛出"FileNotFoundException"意味着可能文件名无效,无法找到该文件;调用者需要聪明地处理这个问题。抛出异常意味着“嘿,该死的事情发生了。交易。”这是一个非常糟糕的API。

在第一篇文章的注释中有一些例子,其中“throws Exception”是一个有效且合理的声明,但对于您所编写的大多数“正常”代码来说,情况并非如此。

简而言之,你的模块或上面的模块在运行时应该处理的异常被称为受控异常;其他是未检查的异常,它们是RuntimeException或Error。

在本视频中,它解释了Java中的受控异常和未受控异常: https://www.youtube.com/watch?v=ue2pOqLaArw

所有异常都必须是检查异常。

Unchecked exceptions are unrestricted gotos. And unrestricted gotos are considered a bad thing. Unchecked exceptions break encapsulation. To process them correctly, all the functions in the call tree between the thrower and the catcher must be known to avoid bugs. Exceptions are errors in the function that throws them but not errors in the function that processes them. The purpose of exceptions is to give the program a second chance by deferring the decision of whether it's an error or not to another context. It's only in the other context can the correct decision be made.