PHP: 异常exception

异常最常见于SDK调用中,函数执行失败时抛出异常,顺带错误码和错误信息。

先来看下PHP的异常处理相关函数:

public Exception::__construct() ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )

构造函数:第一个参数$message为错误信息,第二个参数$code为错误码,第三个参数$previous为前一个异常

函数组:

获取异常的错误码:
final public mixed Exception::getCode ( void )
获取异常的错误信息:
final public string Exception::getMessage ( void )
获取异常发生的文件信息:
final public string Exception::getFile ( void )
获取异常发生在文件的哪一行
final public int Exception::getLine ( void )
获取前一个异常信息:
final public Exception Exception::getPrevious ( void )

最常用的是getCode和getMessage函数。

实例1:

<?php
class test
{
    public function run($num)
    {   
        try{
            $this->process($num);
        } catch (Exception $e) {
            echo sprintf("Errno:%d Error:%s", $e->getCode(), $e->getMessage());
        }   
    }   

    public function process($num)
    {   
        switch($num) {
        case 1: throw new Exception("error", $num);break;
        default:return $num;
        }   
        return;
    }   
}

$app = new test();
$app->run(1);

输出:

Errno:1 Error:error

问题1:异常被抛出后之后的流程会不会执行?答案是:不会的,函数在抛出异常处返回,注意在获取异常处是会继续执行的。

实例2

<?php
class test
{
    public function run($num)
    {
        try{
            $this->process($num);
        } catch (Exception $e) {
            echo sprintf("Errno:%d Error:%s", $e->getCode(), $e->getMessage());
        }
    }

    public function process($num)
    {
        switch($num) {
        case 1: throw new Exception("error", $num);echo "new exception
";break;
        default:return $num;
        }
        return;
    }
}

$app = new test();
$app->run(1);

输出结果:

Errno:1 Error:error

注意:throw之后的echo语句没有被执行。

关于更多Exception的主题说明:http://docs.oracle.com/javase/tutorial/essential/exceptions/advantages.html

原文地址:https://www.cnblogs.com/helww/p/3599110.html