Let's say you have the following hierarchy. You have a base class Animal, with a bunch of sub classes like Cat, Mouse, Dog, etc.
Now, we have the following scenario:
void ftn()
{
throw Dog();
}
int main()
{
try
{
ftn();
}
catch(Dog &d)
{
//some dog specific code
}
catch(Cat &c)
{
//some cat specific code
}
catch(Animal &a)
{
//some generic animal code that I want all exceptions to also run
}
}
So, what I want is that even if a Dog is thrown, I want the Dog catch case to execute, and also the Animal catch case to execute. How do you make this happen?
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.
Starting from Java 7.0, it is possible for a single catch block to catch multiple exceptions by separating each with | (pipe symbol) in the catch block. Catching multiple exceptions in a single catch block reduces code duplication and increases efficiency.
Handle Multiple Exceptions in a catch Block In Java SE 7 and later, we can now catch more than one type of exception in a single catch block. Each exception type that can be handled by the catch block is separated using a vertical bar or pipe | .
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.
Another alternative (aside from the try-within-a-try) is to isolate your generic Animal-handling code in a function that is called from whatever catch blocks you want:
void handle(Animal const & a)
{
// ...
}
int main()
{
try
{
ftn();
}
catch(Dog &d)
{
// some dog-specific code
handle(d);
}
// ...
catch(Animal &a)
{
handle(a);
}
}
AFAIK, you need to split that in two try-catch-blocks and rethrow:
void ftn(){
throw Dog();
}
int main(){
try{
try{
ftn();
}catch(Dog &d){
//some dog specific code
throw; // rethrows the current exception
}catch(Cat &c){
//some cat specific code
throw; // rethrows the current exception
}
}catch(Animal &a){
//some generic animal code that I want all exceptions to also run
}
}
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