Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try- catch. Handling multiple exceptions the same way (or with a fall through)

There has already been a question posted here which is very similar. Mine is extending that question a bit more. Say you want to catch multiple types of exception but want to handle it the same way, is there a way to do something like switch case ?

switch (case)
{
  case 1:
  case 2:

  DoSomething();
  break;
  case 3:
  DoSomethingElse()
  break;

}

Is it possible to handle few exceptions the same way . Something like

try
{
}
catch (CustomException ce)
catch (AnotherCustomException ce)
{
  //basically do the same thing for these 2 kinds of exception
  LogException();
}
catch (SomeOtherException ex)
{
 //Do Something else
}
like image 868
ram Avatar asked Feb 18 '10 19:02

ram


People also ask

How do you handle multiple exceptions in catch block?

If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can't change it. The byte code generated by this feature is smaller and reduce code redundancy.

Is there a way to catch multiple exceptions at once and without code duplication?

In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception.

Can we handle multiple exceptions by using single catch block?

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

Can you have multiple catches in try catch?

Yes, we can define one try block with multiple catch blocks in Java.


3 Answers

Currently there is no language construct to accomplish what you want. Unless the exception all derive from a base exception you need to consider refactoring the common logic to a method and call it from the different exception handlers.

Alternatively you could do as explained in this question:

Catch multiple Exceptions at once?

Personally I tend to prefer the method-based approach.

like image 121
João Angelo Avatar answered Nov 04 '22 21:11

João Angelo


You should really have a BaseCustomException and catch that.

like image 33
pdr Avatar answered Nov 04 '22 19:11

pdr


This is copied from another posting, but I am pulling the code to this thread:

Catch System.Exception and switch on the types

catch (Exception ex)            
{                
    if (ex is FormatException || ex is OverflowException)
    {
        WebId = Guid.Empty;
        return;
    }

    throw;
}

I prefer this to repeating a method call in several catch blocks.

like image 44
Jacob Brewer Avatar answered Nov 04 '22 19:11

Jacob Brewer