Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper use of try .. catch

Should I be using this method of throwing errors:

if (isset($this->dbfields[$var])) {
    return $this->dbfields[$var];
} else {
    throw new FieldNotFoundException($var);
}

or this style:

try {
    return $this->dbfields[$var];
} catch (Exception $e) {
    throw new FieldNotFoundException($var);
}

...or something else altogether?

quick explanation of the code: $this->dbfields is an array. isset() checks if a variable is set, in this case, whether the array element exists.

like image 280
nickf Avatar asked Oct 13 '08 00:10

nickf


People also ask

How do you use try catch effectively?

Generally, you should only use a try-catch if there is something that you can do in the catch. Can you retry the failed connection or otherwise help the user to continue? Do you want to log the exception? If there's nothing you can do to recover or gracefully degrade, there is no point in catching the exception.

What is the purpose of try catch?

Try/catch blocks allow a program to handle an exception gracefully in the way the programmer wants them to. For example, try/catch blocks will let a program print an error message (rather than simply crash) if it can't find an input file. Try blocks are the first part of try/catch blocks.

Should you always use a try catch?

No, you should not wrap all of your code in a try-catch.

When should I use try catch JavaScript?

A try / catch block is basically used to handle errors in JavaScript. You use this when you don't want an error in your script to break your code.


2 Answers

The second example is bad. You're taking a lot of overhead to catch an exception when, as you demonstrate, it's just as easy to prevent the exception in the first place. Plus you also assume you know why that exception was thrown - if there was some other exception, like say an out of memory or something, you're reporting it as a "field not found" even if it wasn't.

Keep in mind that try/catch in languages like C++ and Java are very expensive because of all the state they have to save and restore. Python, on the other hand, has very cheap exceptions and they positively encourage you to use a try/except for simple validation. But even so, catching everything and pretending it's one type of exception is still bad.

like image 195
Paul Tomblin Avatar answered Sep 28 '22 18:09

Paul Tomblin


//First let's do the checks.
if(!isset($this->dbfields[$var]))
    throw new FieldNotFoundException($var);
//Now we're in the clear!
return $this->dbfields[$var];
like image 36
yfeldblum Avatar answered Sep 28 '22 17:09

yfeldblum