Search code examples
androidexceptionthrow

Throw exception and allow to proceed in method further


I was working on some validation. There is some mandatory fields and some of them are optional. For mandatory fields, I'm throwing exception, but for optional fields, I've to print warning and have to proceed further in my method. I'm not getting any way to doing warning part. Can someone help on it?

public void method(String param1, String param2){
 if(param1 == null){
   throw new IllegalArgumentException("mandatory field");
 }
 //Here for param2, I want to throw eception, but want to proceed further to next line.

//Execute my code here

} 

Solution

  • This is not how exceptions work. There are several ways to solve it:

    1. Just don't use exceptions and print your error instead (println() or some textfield, toast or whatever)

    2. Place a boolean marker saying that param2 failed and throw your exception at the end of the method

      m_param2 = true
      //...
      if (param2 == null) {
          m_param2 = false
      }
      // you proceed here
      if (!m_param2){
         // throw exception
      }
      
    3. Use submethods for the parameter-check which always throw an exception when errors occur and catch the error in your main-method and decide what to do then.

    For me case 3 does not make that much sense but that depends on how and when you want to print the message. If you have something in the parent layer (the code that runs your method) that automatically generates the error-message when an exception occurs, I would stick to my second suggestion.

    In general I think that missing optional parameters are no real error case so that no exception should be thrown. The method-caller needs to pass the parameter anyhow (though it can be null, of course).