Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing multiple exceptions in Java

Tags:

java

exception

Is there any way to throw multiple exceptions in java?

like image 223
ajay Avatar asked May 26 '10 11:05

ajay


People also ask

How to throw exceptions in Java?

We specify the exception object which is to be thrown. The Exception has some message with it that provides the error description. These exceptions may be related to user inputs, server, etc. We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception.

Is it possible to throw multiple exceptions at the same time?

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. Show activity on this post. You can throw only one exception at a time. You cannot do what you are asking for.

How do you handle an exception in a method?

Note: If we throw unchecked exception from a method, it is must to handle the exception or declare in throws clause. If we throw a checked exception using throw keyword, it is must to handle the exception using catch block or the method must declare it using throws declaration.

How do you throw an exception in a writelist?

To specify that writeList () can throw two exceptions, add a throws clause to the method declaration for the writeList () method. The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method.


2 Answers

A method can throw one of several exceptions. Eg:

 public void dosomething() throws IOException, AWTException {       // ....  } 

This signals that the method can eventually throw one of those two exceptions (and also any of the unchecked exceptions). You cannnot (in Java or in any language AFAIK) throw simultaneously two exceptions, that would not make much sense.

You can also throw a nested Exception, which contains inside another one exception object. But that would hardly count that as "throwing two exceptions", it just represents a single exception case described by two exceptions objects (frequently from different layers).

like image 144
leonbloy Avatar answered Oct 04 '22 04:10

leonbloy


I suppose you could create an exception containing a list of caught exceptions and throw that exception, e.g.:

class AggregateException extends Exception {     List<Exception> basket; } 
like image 39
JRL Avatar answered Oct 04 '22 04:10

JRL