Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Dynamic or Programmatic Catch Blocks

I have a situation where it would be nice to be able to have a catch block where the type of the Exception is determined at run time. It would work something like this:

$someClassName = determineExceptionClass();

try {
  $attempt->something();
} catch ($someClassName $e) {
  echo 'Dynamic Exception';
} catch (Exception $e) {
  echo 'Default Exception';
}

Is this at all possible?

like image 969
joshwbrick Avatar asked Aug 12 '12 19:08

joshwbrick


People also ask

Which type of catch block is used?

Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType , declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name .

When should you use try catch block PHP?

catch block to catch all exceptions throughout the application which are shown to user as, for example, error 500s and exception is logged with more information to database.

Does catch block always execute?

It always executes, regardless of whether an exception was thrown or caught. You can nest one or more try statements. If an inner try statement does not have a catch -block, the enclosing try statement's catch -block is used instead. You can also use the try statement to handle JavaScript exceptions.


1 Answers

That doesn't work as far as I'm aware. You could mimic that functionality with a control statement like this:

$someClass = 'SomeException';

try
{
    $some->thing();
}
catch (Exception $e)
{
    switch (get_class($e))
    {
        case $someClass:
            echo 'Dynamic exception.';
            break;
        default:
            echo 'Normal exception.';
    }
}
like image 59
Blake Avatar answered Oct 14 '22 14:10

Blake