try...catch捕获不同的异常

目的:想要使用try...catch捕获不同的异常

eg1:

<?php
//创建三个Exception
class AException extends Exception{
    function printMsg(){
        echo "This is AException.";
    }
}
class BException extends Exception{
    function printMsg(){
        echo "This is BException.";
    }
}class CException extends Exception{
    function printMsg(){
        echo "This is CException.";
    }
}


//一个try,多个catch捕获不同的异常
try{
    $flag = 1;
    switch ($flag)
    {
        case 1:
            throw new AException('AException:');
            break;
        case 2:
            throw new BException('BException:');
            break;
        case 3:
            throw new CException('CException:');
            break;
        default:
            break;
    }
}
catch(AException $e){
    echo $e->getmessage();
    $e->printMsg();
}
catch(BException $e){
    echo $e->getmessage();
    $e->printMsg();
}
catch(CException $e){
    echo $e->getmessage();
    $e->printMsg();
}
catch(Exception $e){
    //这个catch主要是捕获漏网之鱼
    echo $e->getmessage();
}

输出:

AException:This is AException.

eg2:

使用了PHP的新特性,一个catch语句块现在可以通过管道字符(|)来实现多个异常的捕获。 这对于需要同时处理来自不同类的不同异常时很有用

try {
    // some code
} catch (FirstException | SecondException $e) {
    // handle first and second exceptions
    if ($e instanceof FirstException ) {
        ....
    }
    ....
} catch (Exception $e) {
    // ...
} finally{
//
}    
原文地址:https://www.cnblogs.com/lyc94620/p/12862794.html