问题
Of course in PHP you can catch all thrown exceptions with:
try{
/* code with exceptions */
}catch(Exception $e) {
/* Handling exceptions */
}
But is there a way to check the exception type of the thrown exception from inside the catch block?
回答1:
You can use get_class:
try {
throw new InvalidArgumentException("Non Sequitur!", 1);
} catch (Exception $e) {
echo get_class($e);
}
回答2:
You can have multiple catch
blocks to catch different Exception types.
See below:
try {
/* code with exceptions */
} catch (MyFirstCustomException $e) {
// We know it is a MyFirstCustomException
} catch (MySecondCustomException $e) {
// We know it is a MySecondCustomException
} catch (Exception $e) {
// If it is neither of the above, we can catch all remaining exceptions.
}
You should know that once an Exception is caught by a catch
statement, none of the following catch
statements will be triggered, even if they match the Exception.
You can also use the get_class
method to get the full class name of any object, including Exceptions.
来源:https://stackoverflow.com/questions/38316800/php-check-thrown-exception-type