Throwing multiple exceptions from a single method

How do you throw several exceptions from one method at once? Example:

public void doA() throws Exception1, Exception2{ throw new Exception1("test1"); throw new Exception2("test2"); } 

How to do something like this work?

Edit: One condition throws both Exception1 and Exception2. Possible? This is just a demo file for checking throw exceptions.

+6
source share
5 answers

You must check that there is something wrong with the method to throw an 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, this is not possible, since throwing an exception will lead to a violation of the method (similar to a return ). You can only throw one Exception at a time.

+9
source

You can use only one exception at a time. You cannot do what you ask. Instead, consider using custom exceptions in your code and use them as appropriate (I'm not sure 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 toss it when you need:

 public void doA() throws Exception1, Exception2{ throw new CustomException("test1, test2"); } 
+1
source

If you have a question, how can you throw more than one exception to a method at a time , then you simply cannot answer. After the first exception is thrown, the control terminates this method, and the exception in its parent method. If there is nothing that catches him, then he goes on to his parent method and so on ...

0
source

I do not think that it is possible to throw more than one exception at a time.

However, depending on the requirement, you can throw a nested exception when you need to pass a context (second) exception:

 throw new Exception("My exception", new Exception("The cause of My Exception")); 
0
source

A throw exception is a one-way transfer of control to another line of code (for example, switching to assembly language). This means that after the throwing statement, the program must optionally execute another line of code outside this area (first, the calling code on the stack that handles this exception).

0
source

All Articles