Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value after throwing exception

Tags:

java

public double get_volume(int a){
  try{
    if (a < 0) {
      // this gets caught in the catch block
      throw new IllegalArgumentException("Only Positive Numbers & no Letters Please!"); 
    }
    return a*a*a;
  } catch (IllegalArgumentException e) {
    System.out.println(e.getMessage());
  }
}

If this function receives a negative value, it will throw an exception to say that it is not allowed. Else, it will proceed to calculate the volume. Somehow I still have to return some value but is it really needed? How do i write this code correctly?

like image 490
Ninja Dude Avatar asked Dec 19 '22 10:12

Ninja Dude


1 Answers

If you are catching the exception inside the method without throwing any exception to the caller (as you currently do), you must return some default value in your catch block.

It would probably make more sense not to catch the exception within the method, which will allow you not to return anything when the exception is thrown. It will also inform the caller they passed invalid input.

public double get_volume(int a)
{
    if (a < 0) {
        throw new IllegalArgumentException("Only Positive Numbers & no Letters Please!"); 
    }
    return a*a*a;      
}

Now it's the responsibility of the caller to handle the exception.

Note that since IllegalArgumentException is an unchecked exception (since it is a sub-class of RuntimeException), you don't need to declare that your method throws this exception. It would be helpful, though, to describe in the Javadoc when you are throwing this exception.

like image 113
Eran Avatar answered Dec 28 '22 23:12

Eran