PHP 检查引发的异常类型

2022-08-30 11:15:26

当然,在 PHP 中,您可以使用以下命令捕获所有抛出的异常:

try{
    /* code with exceptions */
}catch(Exception $e) {
    /* Handling exceptions */
}

但是有没有办法从 catch 块内部检查引发的异常的异常类型?


答案 1

您可以使用get_class

try {
    throw new InvalidArgumentException("Non Sequitur!", 1);
} catch (Exception $e) {
    echo get_class($e);
}

答案 2

您可以使用多个块来捕获不同的异常类型。见下文:catch

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.
}

您应该知道,一旦语句捕获异常,就不会触发以下任何语句,即使它们与 Exception 匹配也是如此。catchcatch

还可以使用该方法获取任何对象(包括 Exceptions)的完整类名。get_class


推荐