asdas
asdas

Reputation: 83

How to catch inherited type of Exception

    +--------+     +-----+
    | a.b.EA |<----|s.EC |
    +--------+     +-----+
     ^      ^
     |      |
  +------+ +------+
  |x.y.EC| |r.l.EC|
  +------+ +------+


pacakge r.l;
public interface X{
    void f() throws a.b.EA;
}

pacakge r.l;
public class M implements X{
    public void f() throws a.b.EA {
        throw new r.l.EC();
    }
}


package x.y;
import r.l.M;
public static void main(String[] args){
    try {
        new M().f();
    }catch(EC e){ (**)
    }
}

And the question is: How to catch exactly instance of EC (because EC says something about cause- EC is like Invalid URL).

M.f() throws r.l.EC() and I can catch r.l.EC. But, other implementation X can throw, for example s.EC, and so on. So, I cannot be prepared. What to do in that situation.

Upvotes: 1

Views: 66

Answers (1)

Eran
Eran

Reputation: 394126

Since you can't know in advance the exact type of exception other implementations of your interface may throw, you can try to catch your specific exception, and then the more general exception:

public static void main(String[] args){
    try {
        new M().f();
    }
    catch(EC e) {
        // specific error handling
    }
    catch(EA e) {
        // more general error handling
    }
}

Upvotes: 1

Related Questions