小编use*_*687的帖子

如何使用异常instanceof改进难看的catch块

请注意:来电者只会抛出parentexception !!

aexception,并bexception继承自parentexception.

在方法af,它throws aexception,bexceptionparentexception.

void af() throws aexception, bexception, parentexception {}
Run Code Online (Sandbox Code Playgroud)

该方法caller调用afthrow parentexception只.

void caller() throws parentexception
Run Code Online (Sandbox Code Playgroud)

在这里,我们丢失了parentexception子类的信息.

该方法rootCaller调用该方法caller,rootcaller并且只能catch parentexception抛出caller并使用以下异常进程catch块:

void rootCaller() {
    try {
        caller(); 
    } catch(parentexception e) {
    if(e instanceof aexception) {
        ......
    } else   if(e instanceof bexception) {
        ......
    } else   if(e instanceof parentexception) {
        ...... …
Run Code Online (Sandbox Code Playgroud)

java exception instanceof inherited

1
推荐指数
1
解决办法
488
查看次数

标签 统计

exception ×1

inherited ×1

instanceof ×1

java ×1