Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing multiple exceptions from one method [closed]

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.

like image 338
user3388925 Avatar asked Mar 06 '14 15:03

user3388925


Video Answer


2 Answers

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");
}
like image 44
Hari Avatar answered Sep 25 '22 05:09

Hari


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.

like image 118
Luiggi Mendoza Avatar answered Sep 23 '22 05:09

Luiggi Mendoza