zoukankan      html  css  js  c++  java
  • 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{
    //
    }    
  • 相关阅读:
    使用PWS调试cgi,php
    解决联想电脑常见故障及内存不足的几种方法
    How Many Tables (并查集)
    Prim
    小希的迷宫(并查集)
    并查集
    Is It A Tree?(并查集)
    hdu 1003 Max Sum(最大子窜和)
    More is better(并查集)
    01背包精讲
  • 原文地址:https://www.cnblogs.com/lyc94620/p/12862794.html
Copyright © 2011-2022 走看看