Bebo
Bebo

Reputation: 23

How can I use an exception without the script dying?

I'd like to use an exception for error handling in a part of my code but if the code should fail, I would like the script to continue. I want to log the error though. Can someone please help me figure this out?


try{
    if($id == 4)
    {
      echo'test';
    }
}
catch(Exception $e){
    echo $e->getMessage();
}

echo'Hello, you should see me...'; <------ I never see this.. No errors, just a trace.

Upvotes: 2

Views: 1533

Answers (2)

Gordon
Gordon

Reputation: 317119

In the code that is calling the code that may throw an Exception do

try { 
    // code that may break/throw an exception
    echo 'Foo';
    throw new Exception('Nothing in this try block beyond this line');
    echo 'I am never executed';
    throw new CustomException('Neither am I');
} catch(CustomException $e) {
    // continue here when any CustomException in try block occurs
    echo $e->getMessage();
} catch(Exception $e) { 
    // continue here when any other Exception in try block occurs
    echo $e->getMessage();
}

// script continues here
echo 'done';

Output will be (adding line breaks for readability):

'Foo'                                         // echoed in try block
'Nothing in this try block beyond this line'  // echoed in Exception catch block
'done'                                        // echoed after try/catch block

Try/Catch Blocks may also be nested. See Example 2 in the PHP Manual page linked above:

try{
    try {
        throw new Exception('Foo');
        echo 'not getting here';
    } catch (Exception $e) {
        echo $e->getMessage();
    }
    echo 'bar';
} catch (Exception $e) {
    echo $e->getMessage();
}
echo 'done';

'Foo'  // echoed in inner catch block
'bar'  // echoed after inner try/catch block
'done' // echoed after outer try/catch block

Further reading at DevZone:

Upvotes: 2

Pascal MARTIN
Pascal MARTIN

Reputation: 401142

You have to catch the exception :

// some code

try {
    // some code, that might throw an exception
    // Note that, when the exception is thrown, the code that's after what
    // threw it, until the end of this "try" block, will not be executed
} catch (Exception $e) {
    // deal with the exception
    // code that will be executed only when an exception is thrown
    echo $e->getMessage(); // for instance
}

// some code, that will always be executed


And here are a couple of things you should read :

Upvotes: 5

Related Questions