How to continue program execution even after throwing exception?

前端 未结 5 1350
盖世英雄少女心
盖世英雄少女心 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:32

    Well first of all ,

    There are 2 types of Exceptions. Checked & Unchecked.

    Unchecked exceptions are the ones that your program cannot recover from. Like NullPointers, telling you that something is really wrong with your logic.

    Checked exceptions are runtime exceptions, and from these ones you can recover from.

    Therefore you should avoid using catch statemens looking for the "Exception" base class. Which are represent both times. You should probably consider looking for specific exceptions(normally sub-classes of Run-Time exceptions).

    In short, there is much more into that.

    You should also keep in mind that you shouldn't use exception handling as workflow. usually indicates that your architecture is somehow deficient. And as the name states, they should be treated as "exceptions" to a normal execution.

    Now, considering you code :

    for(DataSource source : dataSources) {
        try {
            //do something with 'source'
        } catch (Exception e) { // catch any exception
          continue; // will just skip this iteration and jump to the next
        }
       //other stuff ? 
    }
    

    As it is, it should catch the exception and move on. Maybe there is something your not telling us ? :P

    Anyway, hope this helps.

提交回复
热议问题