336

I'd like a cleaner way to obtain the following functionality, to catch AError and BError in one block:

try
{
    /* something */
}
catch( AError, BError $e )
{
    handler1( $e )
}
catch( Exception $e )
{
    handler2( $e )
}

Is there any way to do this? Or do I have to catch them separately?

AError and Berror have a shared base class, but they also share it with other types that I'd like to fall through to handler2, so I can't just catch the base class.

3
  • 7
    Just to add this as a side note: An RFC has been filed for catching multiple exceptions. Let's see if this feature get's it's way into the PHP language ... wiki.php.net/rfc/multiple-catch Commented Apr 22, 2016 at 6:10
  • 14
    ^ This feature has been implemented in PHP 7.1
    – Subin
    Commented Jan 31, 2017 at 7:13
  • In PHP 8.0 there is even cleaner way: stackoverflow.com/a/64159544/7082164
    – JSowa
    Commented Oct 1, 2020 at 16:27

12 Answers 12

536

Update:

As of PHP 7.1, this is available.

The syntax is:

try
{
    // Some code...
}
catch(AError | BError $e)
{
    // Handle exceptions
}
catch(Exception $e)
{
    // Handle the general case
}

Docs: https://www.php.net/manual/en/language.exceptions.php#example-334

RFC: https://wiki.php.net/rfc/multiple-catch

Commit: https://github.com/php/php-src/commit/0aed2cc2a440e7be17552cc669d71fdd24d1204a


For PHP before 7.1:

Despite what these other answers say, you can catch AError and BError in the same block (it is somewhat easier if you are the one defining the exceptions). Even given that there are exceptions you want to "fall through", you should still be able to define a hierarchy to match your needs.

abstract class MyExceptions extends Exception {}

abstract class LetterError extends MyExceptions {}

class AError extends LetterError {}

class BError extends LetterError {}

Then:

catch(LetterError $e){
    //voodoo
}

As you can see here and here, even the SPL default exceptions have a hierarchy you can leverage. Additionally, as stated in the PHP Manual:

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block.

This means you could also have

class CError extends LetterError {}

which you need to handle differently than AError or BError, so your catch statement would look like this:

catch(CError $e){
    //voodoo
}
catch(LetterError $e){
    //voodoo
}

If you had the case where there were twenty or more exceptions that legitimately belonged under the same superclass, and you needed to handle five (or whatever large-ish group) of them one way and the rest the other, you can STILL do this.

interface Group1 {}

class AError extends LetterError implements Group1 {}

class BError extends LetterError implements Group1 {}

And then:

catch (Group1 $e) {}

Using OOP when it comes to exceptions is very powerful. Using things like get_class or instanceof are hacks, and should be avoided if possible.

Another solution I would like to add is putting the exception handling functionality in its own method.

You could have

function handleExceptionMethod1(Exception $e)
{
    //voodoo
}

function handleExceptionMethod2(Exception $e)
{
    //voodoo
}

Assuming there is absolutely no way you can control exception class hierarchies or interfaces (and there almost always will be a way), you can do the following:

try
{
    stuff()
}
catch(ExceptionA $e)
{
    $this->handleExceptionMethod1($e);
}
catch(ExceptionB $e)
{
    $this->handleExceptionMethod1($e);
}
catch(ExceptionC $e)
{
    $this->handleExceptionMethod1($e);
}
catch(Exception $e)
{
    $this->handleExceptionMethod2($e);
}

In this way, you are still have a only single code location you have to modify if your exception handling mechanism needs to change, and you are working within the general constructs of OOP.

7
  • 5
    Here's another vote for this as the correct answer. Unfortunately stuff like what is said in the accepted answer and the fact that it is accepted as the correct answer, is what makes PHP the madness that it is.
    – borfast
    Commented Apr 2, 2014 at 23:31
  • This should be the accepted answer. Although, it assumes that you are able to modify the files. AError could be implemented in a library/file which is updated by a third party.
    – Kayla
    Commented Jul 20, 2014 at 3:50
  • @WaffleStealer654 You can still subclass the files and make those implement your group, even if you can't edit the files directly. That would presume you can throw the exceptions, but you could just wrap the most base-level mechanism where the exception would be throw and then catch it and throw your wrapped exception. Commented Aug 15, 2014 at 16:30
  • 3
    This is not the accepted answer, because you cannot do that when you use a 3rd party library.
    – Denis V
    Commented Aug 25, 2014 at 9:06
  • @DenisV See my comment above yours. It is done all the time in enterprise software. Encapsulation is great. Commented Aug 25, 2014 at 18:28
238

In PHP >= 7.1 this is possible. See this answer.


If you can modify the exceptions, use this answer.

If you can't, you could try catching all with Exception and then check which exception was thrown with instanceof.

try
{
    /* something */
}
catch( Exception $e )
{
    if ($e instanceof AError OR $e instanceof BError) {
       // It's either an A or B exception.
    } else {
        // Keep throwing it.
        throw $e;
    }
}

But it would probably be better to use multiple catch blocks as described in aforementioned answer.

try
{
    /* something */
}
catch( AError $e )
{
   handler1( $e );
}
catch ( BError $b )
{
   handler2( $e );
}
12
  • 6
    That's what I was afraid of. Catching them together and testing the type would be good if there were many error types that needed to be handled together, but for only 2, such as in my case, catching them separately is probably cleaner. Thanks! Commented Dec 9, 2011 at 0:44
  • 3
    @DominicGurto: Yeah, I'd go with that too :) I'd be more concerned with PHP's attitude towards a finally statement. ;)
    – alex
    Commented Dec 9, 2011 at 0:50
  • 7
    But don't forget that this catches ALL exceptions, so there should be something like ... } else { throw($e); } if it doesn't match the two. Sorry for maybe wrong syntax, didn't see php a while. Commented Dec 9, 2011 at 0:51
  • 11
    If you read the first paragraph here: php.net/manual/en/language.exceptions.php you will see multiple catch blocks are possible and perfectly valid solution. The OP though had mistakenly put two exception classes in one catch statement. I think it will be better to update your answer with another example with multiple catch blocks. Commented Aug 7, 2013 at 16:06
  • 4
    Suggesting a solution that eats all your other Exceptions, shouldn't have been accepted at all...
    – Stivni
    Commented Jul 31, 2014 at 12:29
90

Coming in PHP 7.1 is the ability to catch multiple types.

So that this:

<?php
try {
    /* ... */
} catch (FirstException $ex) {
    $this->manageException($ex);
} catch (SecondException $ex) {
    $this->manageException($ex);
}
?>

and

<?php
try {

} catch (FirstException | SecondException $ex) {
    $this->manageException($ex);
}
?>

are functionally equivalent.

0
57

As of PHP 7.1,

catch( AError | BError $e )
{
    handler1( $e )
}

interestingly, you can also:

catch( AError | BError $e )
{
    handler1( $e )
} catch (CError $e){
    handler2($e);
} catch(Exception $e){
    handler3($e);
}

and in earlier versions of PHP:

catch(Exception $ex){
    if($ex instanceof AError || $ex instanceof BError){
        //handle AError and BError
    } elseif($ex instanceof CError){
        //handle CError
    } else {
       throw $ex; // an unknown exception occurred, throw it further
    }
}
0
29

This article covers the question electrictoolbox.com/php-catch-multiple-exception-types. Content of the post copied directly from the article:

Example exceptions

Here's some example exceptions that have been defined for the purposes of this example:

class FooException extends Exception 
{
  public function __construct($message = null, $code = 0) 
  {
    // do something
  }
}

class BarException extends Exception 
{
  public function __construct($message = null, $code = 0) 
  {
    // do something
  }
}

class BazException extends Exception 
{
  public function __construct($message = null, $code = 0) 
  {
    // do something
  }
}

Handling multiple exceptions

It's very simple - there can be a catch block for each exception type that can be thrown:

try 
{
  // some code that might trigger a Foo/Bar/Baz/Exception
}

catch(FooException $e) 
{
  // we caught a foo exception
}

catch(BarException $e) 
{
  // we caught a bar exception
}

catch(BazException $e) 
{
  // we caught a baz exception
}

catch(Exception $e) 
{
  // we caught a normal exception
  // or an exception that wasn't handled by any of the above
}

If an exception is thrown that is not handled by any of the other catch statements it will be handled by the catch(Exception $e) block. It does not necessarily have to be the last one.

3
  • 3
    The problem with this method comes when you have to execute the same code for two or more different Exceptions.
    – Parziphal
    Commented May 14, 2013 at 18:18
  • This was retrieved from Electric Toolbox. Editing post to give credit.
    – Kayla
    Commented Jul 20, 2014 at 3:54
  • With PHP 7.x, you need to catch (Throwable $e) to catch all exceptions. See also: php.net/manual/en/class.throwable.php Commented Jan 11, 2018 at 14:05
23

As an extension to the accepted answer, you could switch the type of Exception resulting in a pattern that is somewhat like the original example:

try {

    // Try something

} catch (Exception $e) {

    switch (get_class($e)) {

        case 'AError':
        case 'BError':
            // Handle A or B
            break;

        case 'CError':
            // Handle C
            break;

        case default:
            // Rethrow the Exception
            throw $e;

    }

}
1
  • 7
    use multiple catches instead of this solution. Commented Oct 7, 2014 at 8:42
6

Here's a reasonable alternative if you don't have control over defining the exceptions. Use the name of the exception variable to categorize the exceptions when they are caught. Then check for the exception variable after the try/catch block.

$ABError = null;
try {
    // something
} catch (AError $ABError) {  // let the exception fall through
} catch (BError $ABError) {  // let the exception fall through
} catch (Exception $e) {
    handler2($e);
}
if ($ABError) {
    handler1($ABError);
}

This somewhat odd looking approach is probably only worth it if there is a lot of duplication between catch block implementations.

5

As of PHP 8.0 you can use even cleaner way to catch your exceptions when you don't need to output the content of the error (from variable $e). However you must replace default Exception with Throwable.

try {
    /* something */
} catch (AError | BError) {
    handler1()
} catch (Throwable) {
    handler2()
}
3
  • this can be done in php >= 7.1 versions too. Commented Jan 5, 2021 at 10:03
  • 2
    No, in previous versions you must write variable name AError $e.
    – JSowa
    Commented Jan 5, 2021 at 12:56
  • 1
    Ohh you skipped capturing the error. Yeah that's new in 8.0. Thank you. Commented Jan 5, 2021 at 13:00
4

Besides fall-through, it's also possible to step over by using goto. It's very useful if you want to see the world burn.

<?php

class A_Error extends Exception {}
class B_Error extends Exception {}
class C_Error extends Exception {}

try {
    throw new A_Error();
} 
catch (A_Error $e) { goto abc; }
catch (B_Error $e) { goto abc; }
catch (C_Error $e) {
abc:
    var_dump(get_class($e));
    echo "Gotta Catch 'Em All\n";
}

3v4l.org

3

Hmm, there are many solution written for php version lower than 7.1.

Here is an other simple one for those who doesn't want catch all exception and can't make common interfaces:

<?php
$ex = NULL
try {
    /* ... */
} catch (FirstException $ex) {
    // just do nothing here
} catch (SecondException $ex) {
    // just do nothing here
}
if ($ex !== NULL) {
    // handle those exceptions here!
}
?>
1

Another option not listed here is to use the code attribute of an exception, so you can do something like this:

try {

    if (1 === $foo) {

         throw new Exception(sprintf('Invalid foo: %s', serialize($foo)), 1);
    }

    if (2 === $bar) {
        throw new Exception(sprintf('Invalid bar: %s', serialize($foo)), 2);
    }
} catch (Exception $e) {

    switch ($e->getCode()) {

        case 1:
            // Special handling for case 1
            break;

        case 2:
            // Special handling for case 2
            break;

        default:

            // Special handling for all other cases
    }
}
3
  • I didn't downvote, but maybe the OOP purists are angry that you didn't create new exception classes using extends \Exception ? Commented Jun 11, 2016 at 15:14
  • Got it. That's the whole point of my solution, you don't need to create arbitrary classes just to establish a namespace to throw a specific exception. Im certain it's why they added the ability to specify a code. Commented Jun 11, 2016 at 17:34
  • I didn't downvote either but I guess downvoters believe that this does not answer the question. I'd suggest starting the answer with something that makes it clear to the reader that you have understood the question and you still want to suggest a total different way for the code flow. This answer really does not answer "how to catch multiple exception types" but rather "how to handle multiple different causes for an exception". Commented Jan 11, 2018 at 14:12
1

A great way is to use set_exception_handler.

Warning!!! with PHP 7, you might get a white screen of death for fatal errors. For example, if you call a method on a non-object you would normally get Fatal error: Call to a member function your_method() on null and you would expect to see this if error reporting is on.

The above error will NOT be caught with catch(Exception $e). The above error will NOT trigger any custom error handler set by set_error_handler.

You must use catch(Error $e){ } to catch errors in PHP7. . This could help:

class ErrorHandler{
    public static function excep_handler($e)
    {
        print_r($e);
    }
}
set_exception_handler(array('ErrorHandler','excep_handler'));
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.