Is there any way to throw multiple exceptions in java?
To throw multiple exceptions in Java you'll first have to suppress each exception into one customized exception and then throw the same customized exception. Please check the below code snippet to achieve the same.
public class AggregateException extends Exception {
public void addException(Exception ex){
addSuppressed(ex);
exception = true;
}
}
public class AnyClass{
public AggregateException aggExcep = new AggregateException();
public void whereExceptionOccurs(){
try{
//some code
}catch(Exception e){
aggExcep.addException(e);
//throw aggExcep;
}
}
}
Call the method addException with the same reference aggExcep wherever you want to(Inside the catch block obviously) suppress any exception. And at the end explicitly throw aggExcep using 'throw' keyword where ever you want to.
The
void addSuppressed(Throwable exception)
is a predefined method of Throwable class which appends the specified exception to the exceptions that were suppressed in order to deliver this exception.