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
}
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.
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.
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.
Yes, we can define one try block with multiple catch blocks in Java.
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.
You should really have a BaseCustomException and catch that.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With