Thread overview
Re: Is there any way I can have one handler for multiple exceptions?
Jul 11, 2011
Jonathan M Davis
Jul 11, 2011
bearophile
Jul 11, 2011
Andrej Mitrovic
July 11, 2011
On 2011-07-11 15:08, Andrej Mitrovic wrote:
> I'm trying to do something like the following:
> 
> import std.exception;
> 
> class Foo : Exception
> {
> this(string msg) { super(msg); }
> }
> 
> class Bar : Exception
> {
> this(string msg) { super(msg); }
> }
> 
> void main()
> {
> try
> {
> }
> catch (Foo) catch (Bar)
> {
> }
> }
> 
> Some function might throw two types of exceptions, but I don't care which one it is, I'd like to handle them both within one catch block. Is this possible?
> 
> My use case is for the cmdln.interact library, I'm using userInput!() to get an integer from the user and the function can throw either a NoInputException or ConvException, but I don't really care which one it is because if either exception is thrown my next action is to use a predefined default.
> 
> Their base class is Exception, but catching all forms of Exceptions is a bad idea.

No. You can only catch one exception type with a particular catch statement. So, if you can't use a base class to catch just the ones that you want to catch, then you have to have separate catch statements for each exception type. But you can always use a function or delegate for the exception handling inside of the catch block if you want to. Or you could catch Exception and then rethrow it if it's not the right type.

- Jonathan M Davis
July 11, 2011
Yeah throwing was one option I thought about. I didn't think about a delegate, that could work. Thanks.
July 11, 2011
Jonathan M Davis:

> No. You can only catch one exception type with a particular catch statement.

I think someone has suggested an enhancement request to allow catching of a sequence of some Exceptions. In Python you are allowed to use a tuple of exceptions for this.

Bye,
bearophile