在Java(或任何其他带有受控异常的语言)中,当创建您自己的异常类时,您如何决定它应该被检查还是未检查?

我的直觉是,在调用者可能能够以某种有效的方式恢复的情况下,将调用checked异常,而作为未检查的异常则更多地用于不可恢复的情况,但我对其他人的想法感兴趣。


当前回答

你是正确的。

未经检查的异常用于让系统快速失效,这是一件好事。为了正常工作,你应该清楚地说明你的方法期望什么。通过这种方式,您可以只验证输入一次。

例如:

/**
 * @params operation - The operation to execute.
 * @throws IllegalArgumentException if the operation is "exit"
 */
 public final void execute( String operation ) {
     if( "exit".equals(operation)){
          throw new IllegalArgumentException("I told you not to...");
     }
     this.operation = operation; 
     .....  
 }
 private void secretCode(){
      // we perform the operation.
      // at this point the opreation was validated already.
      // so we don't worry that operation is "exit"
      .....  
 }

举个例子。关键是,如果系统快速失效,那么你就会知道它在哪里以及为什么会失效。你会得到这样的堆栈跟踪:

 IllegalArgumentException: I told you not to use "exit" 
 at some.package.AClass.execute(Aclass.java:5)
 at otherPackage.Otherlass.delegateTheWork(OtherClass.java:4569)
 ar ......

你会知道发生了什么。“delegateTheWork”方法中的OtherClass(在第4569行)使用“exit”值调用你的类,即使它不应该这样做等等。

否则你将不得不在你的代码中散布验证,这很容易出错。另外,有时很难跟踪哪里出了问题,可能会有几个小时令人沮丧的调试

同样的事情也发生在nullpointerexception中。如果你有一个700行的类,有15个方法,使用30个属性,它们都不能为空,而不是在每个方法中验证可为空性,你可以使所有这些属性都是只读的,并在构造函数或工厂方法中验证它们。

 public static MyClass createInstane( Object data1, Object data2 /* etc */ ){ 
      if( data1 == null ){ throw NullPointerException( "data1 cannot be null"); }

  }


  // the rest of the methods don't validate data1 anymore.
  public void method1(){ // don't worry, nothing is null 
      ....
  }
  public void method2(){ // don't worry, nothing is null 
      ....
  }
  public void method3(){ // don't worry, nothing is null 
      ....
  }

当程序员(你或你的同事)做的每件事都是正确的,验证输入,运行测试,所有的代码都是完美的,但代码连接到第三方web服务可能会关闭(或你正在使用的文件被另一个外部进程删除等)时,检查异常是有用的。web服务甚至可以在连接尝试之前进行验证,但是在数据传输过程中出错了。

在这种情况下,你或你的同事都无能为力。但你还是得做点什么,不能让应用程序在用户眼中消失。你使用一个检查异常来处理异常,当发生这种情况时你能做什么?,大多数时候,只是尝试记录错误,可能会保存你的工作(应用程序工作),并向用户显示消息。(网站blabla宕机,请稍后重试)

如果检查过的异常被过度使用(通过在所有方法签名中添加“throw exception”),那么您的代码将变得非常脆弱,因为每个人都会忽略这个异常(因为太普遍),代码质量将严重受损。

如果过度使用未检查异常,也会发生类似的情况。这段代码的用户不知道是否会出现错误,因此进行了大量的尝试{…}catch(Throwable t)将出现。

其他回答

在任何一个足够大的系统上,有很多层,检查异常是无用的,因为无论如何,您需要一个架构级策略来处理异常将如何处理(使用故障屏障)。

使用受控异常,您的错误处理策略是微管理的,在任何大型系统上都无法承受。

大多数情况下,您不知道错误是否“可恢复”,因为您不知道API的调用者位于哪一层。

假设我创建了一个StringToInt API,用于将整数的字符串表示形式转换为Int。如果API是用“foo”字符串调用的,我必须抛出检查异常吗?它可以恢复吗?我不知道,因为在他的层中,我的StringToInt API的调用者可能已经验证了输入,如果抛出这个异常,它要么是一个错误,要么是一个数据损坏,它是不可恢复的这一层。

在这种情况下,API的调用者不想捕获异常。他只想让异常“冒出来”。如果我选择了一个受控异常,这个调用者将有大量无用的catch块,只能人为地重新抛出异常。

大多数时候,什么是可恢复的取决于API的调用者,而不是API的编写者。API不应该使用受控异常,因为只有未受控异常才允许选择捕获或忽略异常。

我使用的规则是:永远不要使用未经检查的异常!(或者当你看不到任何方法的时候)

从使用您的库的开发人员或使用您的库/应用程序的最终用户的角度来看,遇到由于不应出现的异常而导致应用程序崩溃的情况真的很糟糕。指望包罗万象也不行。

通过这种方式,最终用户仍然可以看到错误消息,而不是应用程序完全消失。

我同意将未检查异常作为规则的偏好,特别是在设计API时。调用方总是可以选择捕获记录在案的、未检查的异常。你只是没有必要强迫打电话的人。

I find checked exceptions useful at the lower-level, as implementation detail. It often seems like a better flow of control mechanism than having to manage a specified error "return code". It can sometimes help see the impact of an idea for a low level code change too... declare a checked exception downstream and see who would need to adjust. This last point doesn't apply if there are a lot of generic: catch(Exception e) or throws Exception which is usually not too well-thought out anyway.

当不太可能出现异常时,即使在捕捉到异常之后,我们也可以继续,并且我们不能做任何事情来避免该异常,那么我们可以使用受控异常。

当我们想做一些有意义的事情时,当一个特定的异常发生时,当这个异常是预期的,但不是确定的,那么我们可以使用受控异常。

当异常在不同的层中导航时,我们不需要在每一层都捕获它,在这种情况下,我们可以使用运行时异常或包装异常作为未检查的异常。

运行时异常是在异常最有可能发生的情况下使用的,没有办法进一步进行,并且没有任何东西可以恢复。在这种情况下,我们可以对这种异常采取预防措施。EX: NUllPointerException, ArrayOutofBoundsException。这些更有可能发生。在这种情况下,我们可以在编码时采取预防措施来避免这种异常。否则,我们将不得不在每个地方都写入try catch块。

更一般的例外情况可以设置为Unchecked,不太一般的例外情况将被检查。

来自Java学习者:

When an exception occurs, you have to either catch and handle the exception, or tell compiler that you can't handle it by declaring that your method throws that exception, then the code that uses your method will have to handle that exception (even it also may choose to declare that it throws the exception if it can't handle it). Compiler will check that we have done one of the two things (catch, or declare). So these are called Checked exceptions. But Errors, and Runtime Exceptions are not checked for by compiler (even though you can choose to catch, or declare, it is not required). So, these two are called Unchecked exceptions. Errors are used to represent those conditions which occur outside the application, such as crash of the system. Runtime exceptions are usually occur by fault in the application logic. You can't do anything in these situations. When runtime exception occur, you have to re-write your program code. So, these are not checked by compiler. These runtime exceptions will uncover in development, and testing period. Then we have to refactor our code to remove these errors.