When to choose checked and unchecked exceptions

前端 未结 18 2267
南方客
南方客 2020-11-22 04:13

In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked?

My inst

18条回答
  •  情深已故
    2020-11-22 05:03

    You're correct.

    Unchecked exceptions are used to let the system fail fast which is a good thing. You should clearly state what is your method expecting in order to work properly. This way you can validate the input only once.

    For instance:

    /**
     * @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"
          .....  
     }
    

    Just to put an example. The point is, if the system fails fast, then you'll know where and why it did fail. You'll get an stacktrace like:

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

    And you'll know what happened. The OtherClass in the "delegateTheWork" method ( at line 4569 ) called your class with the "exit" value, even when it shouldn't etc.

    Otherwise you would have to sprinkle validations all over your code and that's error prone. Plus, sometimes it is hard to track what went wrong and you may expect hours of frustrating debugging

    Same thing happens with NullPointerExceptions. If you have a 700 lines class with some 15 methods, that uses 30 attributes and none of them can be null, instead of validating in each of those methods for nullability you could make all those attributes read-only and validate them in the constructor or factory method.

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

    Checked exceptions Are useful when the programmer ( you or your co-workers ) did everything right, validated the input, ran tests, and all the code is perfect, but the code connects to a third party webservice that may be down ( or a file you were using was deleted by another external process etc ) . The webservice may even be validate before the connection is attempted, but during the data transfer something went wrong.

    In that scenario there is nothing that you or your co-workers can do to help it. But still you have to do something and not let the application just die and disappear in the eyes of the user. You use a checked exception for that and handle the exception, what can you do when that happens?, most of the time , just to attempt to log the error, probably save your work ( the app work ) and present a message to the user. ( The site blabla is down, please retry later etc. )

    If the checked exception are overused ( by adding the "throw Exception" in the all the methods signatures ) , then your code will become very fragile, because everyone will ignore that exception ( because is too general ) and the quality of code will be seriously compromised.

    If you overuse unchecked exception something similar will happen. The users of that code don't know if something may go wrong an a lot of try{...}catch( Throwable t ) will appear.

提交回复
热议问题