c# – Using try-catch block in a function – Education Career Blog

This really isn’t an important question. I just wanted to know which method is more popular and whether there’s some sort of a de facto standard.

This,

function foobar
{
    int retVal = 0;
    try
    {
        retVal+=100;
    }
    catch 
    {
        //error handling code
    }
    return retVal;
}

Or this?

function foobar
{
    try
    {
        return 100;
    }
    catch 
    {
        //error handling code
    }
    return 0;
}

,

It really depends upon what the function is doing. Use of a retVal variable is useful when then function need to go though a few operations to construct the return value. If the return value is more atomic than that I wouldn’t bother with the extra variable.

,

Unfortunately this very much depends on the exception you expect to occur, and IF the function should return a default value in the event of an exception.

This will also be influenced by the function itself, as I find in smaller utility functions it is easy to read and see where the function returns, and what it will be returning, as where it is sometimes more applicable to have more than one return point as business logic/normal logic would make this more understandable.

So both is acceptable…

,

This question hasn’t got much to do with try catch as it does with coding styles. In the first option you have only return path for the function, while in the second you have many.

Other then coding style, in the case of more then one return path, the you may still see the first option, but that is dependent on the code in question.

I try to avoid more then one return path to the function. I find it easier to read for my team (they do the same, because it is in a part of our guide lines).

,

It will be safe to return in the end simple because if you had a finally block or some other things to clean up after, returning prematurely may lead to errors.

,

The first one is my choice if the try catch has several processes that would affect the returning value. The second one is fitted if you want to return a constant value.

,

I find this more readable (put the return inside the catch block):

function foobar
{
    try
    {
        return 100;
    }
    catch 
    {
        //error handling code
        return 0;
    }
}

Leave a Comment