Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/245.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 尝试多重捕捉_Php_Exception_Try Catch - Fatal编程技术网

Php 尝试多重捕捉

Php 尝试多重捕捉,php,exception,try-catch,Php,Exception,Try Catch,这是我的密码: error_reporting(0); $mysqli=new mysqli("localhost",'root','','alex'); try{ if($mysqli->connect_errno){ throw new Exception("Database error!"); }else{ $query=$mysqli->query("Select companie,sum(suma) as suma from

这是我的密码:

error_reporting(0);

$mysqli=new mysqli("localhost",'root','','alex');
try{
    if($mysqli->connect_errno){
        throw new Exception("Database error!");
    }else{
        $query=$mysqli->query("Select companie,sum(suma) as suma from muncitori group by companie");
        if(!$query){
            throw new LastException("Query failed!");
        }
    }
    while($result=$query->fetch_array()){
        echo "Compania $result[companie] a cheltuit suma $result[suma] lei<br>";
    }
}catch (Exception $e){
    echo $e->getMessage();
}catch (LastException $e){
    echo $e->getMessage();
}
class LastException extends Exception{}
错误报告(0);
$mysqli=newmysqli(“localhost”、“root”、“alex”);
试一试{
如果($mysqli->connect\u errno){
抛出新异常(“数据库错误!”);
}否则{
$query=$mysqli->query(“按公司从muncitori group中选择公司,sum(suma)作为suma”);
如果(!$query){
抛出新的LastException(“查询失败!”);
}
}
而($result=$query->fetch\u array()){
echo“Compania$result[companie]a cheltuit suma$result[suma]lei
”; } }捕获(例外$e){ echo$e->getMessage(); }捕获(上次例外$e){ echo$e->getMessage(); } 类LastException扩展异常{}

如果查询失败并抛出异常,(LastException$s)catch块不会捕获异常,而是(exception$e)捕获它。问题在哪里?为什么异常捕获异常而不是上次异常?

反转这两个异常:

} catch (LastException $e) {
    echo $e->getMessage();
} catch (Exception $s) {
    echo $s->getMessage();
}

您应该重新排列捕捉块:从最具体到最一般,例如:

需要知道的事情:

  • 捕捉块按顺序处理:从上到下
  • 将执行第一个匹配的catch块

因此,如果您首先放置
}catch(Exception$e)
,那么它将捕获所有异常,因为
Exception
是PHP中所有异常的基类。

请重新表述您的问题谢谢,这就是问题所在!
try {
   //...
} catch (LastException $e) {
   //...
} catch (Exception $e) {
   //...
}