public class try
{
public static void main(String[] args)
{
try
{
if(true)
throw new A();
if(true)
throw new B();
}
catch( A | B e)
{
e.doit();
}
}
}
class A extends Exception
{
public void doit() {}
}
class B extends Exception
{
public void doit() {}
}
This doesn't compile
18: error: cannot find symbol
e.doit();
^
symbol: method doit()
location: variable e of type Exception
The variable e
seems to end up as type Exception
rather than the actual type - this seems logical because at compile type the compiler doesn't know what kind is going to be thrown. However, is there a way to make this work without making A
& B
both derive from some common base class or implement a common interface?
Java allows you to catch multiple type exceptions in a single catch block. It was introduced in Java 7 and helps to optimize code. You can use vertical bar (|) to separate multiple exceptions in catch block.
When catching multiple exceptions in a single catch block, the rule is generalized to specialized. This means that if there is a hierarchy of exceptions in the catch block, we can catch the base exception only instead of catching multiple specialized exceptions.
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.
The * symbol indicates that multiple exceptions can be handled by each except* clause. try: raise ExceptionGroup('Example ExceptionGroup', ( TypeError('Example TypeError'), ValueError('Example ValueError'), KeyError('Example KeyError'), AttributeError('Example AttributeError') )) except* TypeError: ...
Well no, because Java doesn't support duck typing.
Doing an instanceof
and casting e
to either A
or B
is obviously going to work, but what you probably want to do in this case is doing it in the traditional way of writing two catch blocks.
I mean, it makes sense, right? Multi-catch is appropriate in the case where you want to treat different kinds of exceptions equally. In this case, the behaviour can be drastically different (even if the methods are named the same).
You should just create a super class that both A and B extend, give that class an doIt() method, and then implement that method for both A and B, like this:
class A extends C {
public void doit() {
}
}
class B extends C {
public void doit() {
}
}
abstract class C extends Exception {
public abstract void doit();
}
You can then catch C, like this:
try
{
if(true)
throw new A();
if(true)
throw new B();
}
catch( C e)
{
e.doit();
}
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