Question

I have a method which might receive invalid input values or a output with associated error messages.

For both the cases I would like to throw an exception.So both of these might occur in a single method call.So how can this be handled as a single exception when the exceptions can happen simultaneously !!

Was it helpful?

Solution

Looks like you're trying to use exceptions for validation. This might work but if you want to get everything which is wrong with the thing you're trying to validate, then you need to do something different. A bit of pseudocode to give you a general idea:

public ValidationResult validateInput(Input input) {
    ValidationResult result = new ValidationResult();
    if (input.someField() == null) {
      result.addError("Some field cannot be null");
    }
    //etc
    return result;
 }

The idea is that you have a ValidationResult object which will store everything which is wrong with the input. Once the validation is done you can process it like that:

ValidationResult result = validateInput(someInput);
if (result.hasErrors()) {
 for (ErrorMessage message : result.getErrors()) {
   log.error(message.getMessage());
 } else {
   //success
}

You can write your own ValidationResult class or research into validation frameworks to find one which works for the purpose.

OTHER TIPS

It's impossible that more than one exception gets thrown at the same time, if your method is declared to throw several exceptions, it'll always be the case that one of them gets thrown first. For instance:

public void method() throws Exception1, Exception2 {
    if (firstCondition)
        throw new Exception1();
    if (secondCondition)
        throw new Exception2();
    // body of method
}

In the above toy example, either the first or the second condition will occur, but they can't happen simultaneously, one of them will be true first and then the corresponding exception will be raised.

Two exceptions can't never happen simultaneously.

When one exception is thrown, the other one does not matter, because code flow is no longer on that method.

It's impossible for a piece of code to throw more than one exception simultaneously. The first one triggered in the code path would be thrown.

Each thread has one stack, and the exception means a frame pops up which means returning to the caller. So no, it makes no sense if two exceptions happen at the same time in the same thread.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top