I am very new to programming in general, while reading about PHP I saw try {}
and catch {}
and was wondering if anyone could help me with what they mean?
Asked
Active
Viewed 262 times
0
-
1http://stackoverflow.com/questions/933081/try-catch-statements-in-php This can be useful. – Apr 05 '12 at 04:15
-
1this is super basic, I suggest you pick up a good PHP book and start reading so you understand the fundamentals of programming. – jb. Apr 05 '12 at 04:15
2 Answers
2
Entry level primer to exceptions:
function doSomething($arg1)
{
if (empty($arg1)) {
throw new Exception(sprintf('Invalid $arg1: %s', $arg1));
}
// Reached this point? Sweet lets do more stuff
....
}
try {
doSomething('foo');
// Above function did not throw an exception, I can continue with flow execution
echo 'Hello world';
} catch (Exception $e) {
error_log($e->getMessage());
}
try {
doSomething();
// Above function DID throw an exception (did not pass an argument)
// so flow execution will skip this
echo 'No one will never see me, *sad panda*';
} catch (Exception $e) {
error_log($e->getMessage());
}
// If you make a call to doSomething outside of a try catch, php will throw a fatal
// error, halting your entire application
doSomething();
By placing function/method calls within a try/catch block you can control the flow execution of your application.

Mike Purcell
- 19,847
- 10
- 52
- 89