How do you throw more than one exception at once from one method? Example:
public void doA() throws Exception1, Exception2{
throw new Exception1("test1");
throw new Exception2("test2");
}
How to make something like this work?
Edit : one condition throws both Exception1 and Exception2. Possible? This is just a demo file to test throwing exceptions.
You can throw only one exception at a time. You cannot do what you are asking for. Instead, think about using custom exceptions in your code, and use them, depending on the situation (I am not sure about the reason why you need to throw two exceptions) :
class CustomException extends Exception
{
//Parameterless Constructor
public CustomException() {}
//Constructor that accepts a message
public CustomException(String message)
{
super(message);
}
}
and then throw it when you need to:
public void doA() throws Exception1, Exception2{
throw new CustomException("test1, test2");
}
You should check if something is not right in the method to throw the Exception
. Here's a sample:
public void doA() throws Exception1, Exception2 {
if (<some unexpected condition>) {
throw new Exception1("test1");
}
if (<another unexpected condition>) {
throw new Exception2("test2");
}
//rest of the implementation...
}
If you mean how to throw several exceptions at the same time, that's not possible since throwing a exception will break the execution of the method (similar to a return
). You can only throw one Exception
at a time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With