Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continue program execution even after throwing exception?

Tags:

java

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

for(DataSource source : dataSources) {
    try {
        //do something with 'source'
    } catch (Exception e) {
    }
}

If exception is thrown in the first iteration, flow execution is stopped. My requirement is even after throwing exception for the first iteration, other iterations should continue. Can i write logic in catch block?

like image 582
user1016403 Avatar asked May 02 '12 11:05

user1016403


People also ask

How do I continue after exception is caught?

If an exception is caught and not rethrown, the catch() clause is executed, then the finally() clause (if there is one) and execution then continues with the statement following the try/catch/finally block.

Is it possible to resume Java execution after exception occurs?

No. You cannot just jump back into the middle of a method.

Does program stop after throwing exception?

The program execution is still interrupted if an exception is thrown from the divide method. Thus the "System. out. println(result);" method will not get executed if an exception is thrown from the divide method.

How do you throw an exception without stopping a program?

To print an exception without exiting the program, use a try/except block and assign the exception object to variable e using except Exception as e . Now, call print(e) in the except branch to print a simple error message.


1 Answers

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.

like image 165
ehanoc Avatar answered Nov 03 '22 20:11

ehanoc