Search code examples
javaif-statementexceptionthrow

Throw exceptions without using if - Java


Is there a way to throw an exception in your function without using an if statement in Java? For example, if an integer is smaller than 0, I want to throw an exception, but when checking that specific condition, I don't want to use an if(or switch) statement.


Solution

  • You can assign different types of exceptions to a variable using the ternary operator and then throw the exception.

    Then you can handle the case where number is smaller than 0 by catching that specific exception and re-throwing it. The other Exception should have an empty catch.

    int number = 0;
    
    RuntimeException result = number < 0 ? new NumberFormatException() : new RuntimeException();
    
    try {
        throw result;
    } catch (NumberFormatException e) {
        throw e;  
    } catch (RuntimeException e) {
        // Do nothing
    }