dreinoso
dreinoso

Reputation: 1689

Inside a try block should only be the instructions that could throw the exception or can put some code not relevant for the exception?

If i know that only one function (take in the example) will throw the exception, what could be the correct way, of the following options?

  1. All in the try block:

    try
    {
        while (someCondition)
        {
            take();   
            anotherFunction();
        }
    }
    catch(Exceotion e)
    {
        //some instructions
    }
    
  2. Inside the block only the function that throw the exception:

    while (someCondition)
        {
            try
            { 
                take();   
            }
            catch....
            {
                 //some instructions
            }
            anotherFunction();
        }       
    

I would use the first way because it's clearer, but there is an explicit rule about this?

Thanks!

Upvotes: 0

Views: 43

Answers (1)

Thilo
Thilo

Reputation: 262724

The two ways do very different things and depending on what you need the code to do, either can be correct.

In the first example, anotherFunction is not called if there was an exception.

In the second example, the exception is being dealt with in the catch block, and anotherFunction will be executed afterwards.

Along the same lines, in the first example, an exception aborts the whole while loop, whereas in the second example it aborts only a single iteration and continues the loop with the next iteration.

Upvotes: 1

Related Questions