Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to catch exceptions?

Would there be any difference If i do the following without using exceptions?

void func()
{
    try
    {
        if (n > 5)
        {
            throw "n is greater than 5";
        }
    }
    catch (const char *e)
    {
        MessageBox(0, e, 0, 0);
        return;
    }
}

OR

void func()
{
    if (n > 5)
    {
       MessageBox(0, "n is greater than 5", "Error", 0);
       return;
    }
}
like image 257
user963241 Avatar asked Nov 05 '10 10:11

user963241


People also ask

When should you not catch exception?

Don't catch exceptions when you don't want to. Just don't. Instead, let them trickle up the call tree until either you have a good solution or you hit the main function, in which case you can be sure that error information is correctly routed.

Should I always catch exceptions?

You should always list catched exceptions. They are predicted. If you want to catch unpredicted exceptions and handle them the same way, you should catch RuntimeException instead.

When should exceptions be used?

Exceptions should be used for situation where a certain method or function could not execute normally. For example, when it encounters broken input or when a resource (e.g. a file) is unavailable. Use exceptions to signal the caller that you faced an error which you are unwilling or unable to handle.

Why do we catch exceptions?

Catch an exception when there's an anticipated problem downstream that you can handle somehow. For example, you might catch exceptions indicating network problems and retry the operation a couple of times, or you might display an error message to the user and ask what to do next.


1 Answers

I would probably say that you best advised not to use exceptions for flow control. Exceptions, as the name suggests, are for handling exceptional circumstances. In the above case you're clearly expecting n to possibly be > 5 so it's not really an exceptional circumstance. If there is a way for your application to deal with that case, then it should do so in preference to raising an exception.

I'm sure there are cases where that logic falls down but in general I think that's a good rule of thumb.

But in technical terms there isn't much difference (possibly performance if you're doing it a lot).

like image 53
wjbeau Avatar answered Sep 22 '22 16:09

wjbeau