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();
}
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.
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.
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.
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 ) { // ... }
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With