How to continue program execution even after throwing exception?

前端 未结 5 1352
盖世英雄少女心
盖世英雄少女心 2021-02-05 23:56

I have a requirement where in program execution flow should continue even after throwing an exception.

for(DataSource source : dataSources) {
    try {
        /         


        
5条回答
  •  情歌与酒
    2021-02-06 00:29

    If you are not breaking the loop somehow inside the catch block, then the other iterations will just continue, regardless of whether an exception was thrown in a previous iteration.

    Try this simple example and see what happens:

    List list = new ArrayList();
    list.add("1");
    list.add("2");
    list.add("3");
    
    for(String str: list) {
       try {
           System.out.println(str);
           throw new Exception("Exception for string " + str);
       } catch(Exception ex) {
           System.out.println("Caught exception");
       }
    }
    

    You will see that all iteration execute, even though each one throws an exception.

提交回复
热议问题