当然,在PHP中,你可以通过以下方式捕获所有抛出的异常:
try{
/* code with exceptions */
}catch(Exception $e) {
/* Handling exceptions */
}
但是有没有办法从 catch 块内部检查抛出的异常的异常类型?
您可以使用
get_class
:
try {
throw new InvalidArgumentException("Non Sequitur!", 1);
} catch (Exception $e) {
echo get_class($e);
}
您可以有多个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.
}
您应该知道,一旦 catch
语句捕获异常,就不会触发以下 catch
语句中的任何一个,即使它们与异常匹配。
还可以使用 get_class
方法获取任何对象的完整类名,包括异常。
我认为使用实例是一个更好的解决方案,因为它为您提供的信息不仅仅是您从get_class
获得的类名。
class db_exception extends Exception {}
class db_handled_exception extends db_exception {}
class db_message_exception extends db_exception {}
function exception_type($ex){
echo '<pre>';
echo 'Type: [' . get_class($ex) . "]'n";
echo "Instance of db_message_exception? " . var_export($ex instanceof db_message_exception,true) . "'n";
echo "Instance of db_handled_exception? " . var_export($ex instanceof db_handled_exception,true) . "'n";
echo "Instance of db_exception? " . var_export($ex instanceof db_exception,true) . "'n";
echo "Instance of Exception? " . var_export($ex instanceof Exception,true) . "'n";
echo '</pre>';
}
exception_type(new db_handled_exception());
exception_type(new db_message_exception());
exception_type(new db_exception());
exception_type(new exception());
这将产生如下结果
Type: [db_handled_exception]
Instance of db_message_exception? false
Instance of db_handled_exception? true
Instance of db_exception? true
Instance of Exception? true
Type: [db_message_exception]
Instance of db_message_exception? true
Instance of db_handled_exception? false
Instance of db_exception? true
Instance of Exception? true
Type: [db_exception]
Instance of db_message_exception? false
Instance of db_handled_exception? false
Instance of db_exception? true
Instance of Exception? true
Type: [Exception]
Instance of db_message_exception? false
Instance of db_handled_exception? false
Instance of db_exception? false
Instance of Exception? true
在某些情况下,您可能需要对异常进行分类并执行常见操作。
考虑到上面的示例,您可能只想显示类型 db_message_exception
和 db_handled_exception
的异常;在这种情况下,由于它们都是从db_exception继承的,您可以简单地说:
if ($ex instanceof db_exception){
// show error message
}
您可能还希望包装异常,以避免将太多信息溢出到客户端屏幕:
if (!($ex instanceof db_exception)){
throw new db_handled_exception('an unhandled exception occured', -1, $ex)
}