Dennis Haarbrink
Dennis Haarbrink

Reputation: 3760

Exceptions: re-throw and multiple catch blocks

I have a situation where I would like to re-throw an exception inside a catch block and have it caught by a more generic catch.

Example:

try {
    somethingThatMightThrowExceptions();
}
catch (ClientErrorResponseException $e) {
    if ($e->getResponse()->getStatusCode() == 404) {
        return $this->notFound();
    }
    throw $e; // even tried throw new \Exception();
}
catch (\Exception $e) {
    return $this->serverError('Server error');
}

So in my first catch block I check for a specific condition, and if that fails I would like to re-throw the exception and have it caught by the generic catch (\Exception) block. But in this case it just bubbles back up to the caller.

The problem is that there are actually a couple more lines of code in the final catch, which I don't want to repeat. I could of course extract them to a method, but that feels like overkill.

So basically I want to do it all in-line without having to add extra layers. Any suggestions?

Upvotes: 3

Views: 1651

Answers (3)

fred727
fred727

Reputation: 2854

You have two options:

a) Catch the most generic exception and check for its type, as @deceze suggested

try{
    somethingThatMightThrowExceptions();
}
catch (\Exception $e) { // The most generic exception
    if($e instanceof ClientErrorResponseException) {
       // Some actions specific to ClientErrorResponseException
    }

    // Shared actions
}

b) Put anoter try/catch block at upper level

try {
    try {
        somethingThatMightThrowExceptions();
    }
    catch (ClientErrorResponseException $e) {
        // Some actions specific to ClientErrorResponseException
        throw $e ;
    }
}
catch (\Exception $e) { // The most generic exception
    // Shared actions
}

Upvotes: 0

igaster
igaster

Reputation: 13663

You have two options: a) Extract common logic to a method. (This can be overkill sometimes as you've mentioned) b) Catch the most generic exception and check for its type. ie:

try{
    somethingThatMightThrowExceptions();
}
catch (\Exception $e) { // The most generic exception
    if($e instanceof ClientErrorResponseException) {
       // Some actions specific to ClientErrorResponseException
    }

    // Shared actions
}

Upvotes: 1

ek9
ek9

Reputation: 3442

It's due to catch only working once as you are throwing an exception not withing a try block. If you are determined, that you want to do it this way, then you need to nest try..catch statements as @deceze suggested in comments..

You should describe what you are trying to accomplish instead, as there might be a better way to do it.

Upvotes: 3

Related Questions