5
Reply

Where to use Try/Catch block?

Adam

Adam

Sep 13 2011 11:34 AM
1.6k
Hi

First of all please forgive me, I seem to be having a bit of a mental block!  I've been trying to improve my exception handling and error logging.

I have a function ChangeName().  Within that function I call a ValidateUser() function.  And within that function I call the GetAdmin() function.

I have omitted unimportant code, so:

public void ChangeName(...)
{
        if(ValidateUser())
                //Do stuff
        else
                //log error
}

public bool ValidateUser(...)
{
        if(IsAuthenticated && GetUser(...))
                return true;
        else return false;
}

public bool GetUser(...)
{
        //Access DB and if found
                return true;
        else
                return false;
}

My question is, where should I have the try/catch blocks?
Do I just have it in ChangeName() so that all errors propogate back to this function, or do I have one in each function?  I'm trying to get my head around which is best practice.  I also realise that I shouldn't just catch Exception, but catch specific types first.

Thanks

Answers (5)