Try/Multi-Catch vs Single Catch

后端 未结 5 951
北荒
北荒 2021-01-11 17:16

While adding a try/catch block in Eclipse, it gave me the option of \"Surround with try/multi-catch\" or \"Surround with try/catch.\"

This is the try/multi-catch:

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-11 17:48

    If you want to do the same thing for all exceptions, try-multi catch and try-catch are the same, except the former is shorter. All programmers are lazy.

    When you want to do different thing for different exceptions:

    } catch(AException e) {
        System.err.println("AException occured");
    } catch(BException e) {
        System.err.println("BException occured");
    }
    

    Try-multi catch is not the right choice.


    } catch(AException | BException e) {
        System.err.println("A or B Exception occured");
    }
    

    Note that the type of e is the nearest common supertype of AException and BException.

提交回复
热议问题