0 votes
by (2.5k points)

I understand that using a finally means that no matter what happens in the try catch block, it will run. But is it needed if I'm just running code after the try catch anyway? 

Something like this? 

try
{
    //Do Work
} catch (Exception ex)
{
    //Log the exception
}

//Then continue with work

Won't the code underneath run anyway?

1 Answer

0 votes
by (2.5k points)

In the example, if you "swallow" the exception it's not going to make too much of a difference. But finally is really important should the catching of the exception change the control flow of the application. For example : 

try
{
    //Do Work
} catch (Exception ex)
{
    //Log the exception
	throw; //This then exits the function/app
} finally
{
	//Do the additional work in a finally block
}

//Anything down here won't be called

Another example might be when the catch actually calls return or break like so : 

try
{
    //Do Work
} catch (Exception ex)
{
    //Log the exception
	return; //Stop processing
} finally
{
	//Do the additional work in a finally block
}

//Anything down here won't be called

Regardless, it's a pretty good habit to get into the groove of using finally statements, especially for things like releasing connections/locks. Even if you are sure the code will continue below the try/catch, there is no guarantee that another developer won't come along and change what your catch statement does, and not know that the code below MUST be run. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.
...