• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to throw an exception that has multiple causes?  RSS feed

 
Vimil Saju
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically this is the scenario.

I have a function A that in a loop makes a call to another function B. Function B can fail due to different reasons and for each reason it throws a specific type of exception.

Function A has to proceed with the next iteration of the loop irrespective of whether function B succeeds or fails in any iteration of the loop.

Once the loop has executed, function A has to collect the exceptions thrown by function B in all iterations it failed, wrap it into one exception and throw this exception.

here's an example of the above scenario


[ November 05, 2008: Message edited by: Martijn Verburg ]
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch

That sounds a peculiar requirement. You could try a customised Exception which has a List<Exception> as a field, and an add(Exception ex) method.

But it is worth finding out why that strange behaviour is required in the first place.
 
Martijn Verburg
author
Bartender
Posts: 3275
5
Eclipse IDE Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

Just a quick tip for your future posts, you can UseCodeTags to make your code stand out, it's easier for us all to read it that way
 
Rory Marquis
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A slight variation on what Campbell said, you could create your own Exception that accepted a List of Exceptions in it's constructor and then had getAllCauses() function in it.

This would mean it couldn't have other Exceptions added to it after it left your method.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's just one small problem with that: printStackTrace will not print those causes unless you override those methods as well.
 
Rory Marquis
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good point Rob.

Or you could create an object to hold the exception and the stack trace for each.
[ November 05, 2008: Message edited by: Rory Marquis ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!