Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rethrow php exception into higher level catch block

I am trying to pass an exception from a specific catch block to a more general catch block. However it does not appear to be working. I get a 500 server error when I try the following. Is this even possible?

I realize that there are easy workarounds, but isn't it normal to say, "Hey I don't feel like dealing with this error, let's have the more general exception handler take care of it!"

try {
   //some soap stuff
}

catch (SoapFault $sf) {
    throw new Exception('Soap Fault');
}

catch (Exception $e) {
     echo $e->getMessage();
}
like image 308
mrtsherman Avatar asked Jun 16 '11 19:06

mrtsherman


People also ask

Is it possible to rethrow a caught exception?

If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression ( throw without assignment_expression) causes the originally thrown object to be rethrown.

Can we throw exception from catch block PHP?

The exception within the checkNum() function is thrown. The "catch" block retrieves the exception and creates an object ($e) containing the exception information. The error message from the exception is echoed by calling $e->getMessage() from the exception object.

What is Rethrow in exception handling?

Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only be used inside a catch block.

How can I catch exception in PHP?

Because exceptions are objects, they all extend a built-in Exception class (see Throwing Exceptions in PHP), which means that catching every PHP exception thrown is as simple as type-hinting the global exception object, which is indicated by adding a backslash in front: try { // ... } catch ( \Exception $e ) { // ... }


1 Answers

Technically this is what you're looking for:

try {
    try {
       //some soap stuff
    }    
    catch (SoapFault $sf) {
        throw new Exception('Soap Fault');
    }
}
catch (Exception $e) {
     echo $e->getMessage();
}

however I agree that exceptions shouldn't be used for flow control. A better way would be like this:

function show_error($message) {
    echo "Error: $message\n";
}

try {
   //some soap stuff
}    
catch (SoapFault $sf) {
    show_error('Soap Fault');
}
catch (Exception $e) {
    show_error($e->getMessage());
}
like image 198
Chris Eberle Avatar answered Oct 05 '22 04:10

Chris Eberle