0

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?

rlemon
  • 17,518
  • 14
  • 92
  • 123
NewUser
  • 12,713
  • 39
  • 142
  • 236
  • 1
    http://stackoverflow.com/questions/933081/try-catch-statements-in-php This can be useful. –  Apr 05 '12 at 04:15
  • 1
    this 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 Answers2

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
1

PHP has pretty good documentation - you should start there:

http://php.net/manual/en/language.exceptions.php

Colin Brock
  • 21,267
  • 9
  • 46
  • 61