欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

php抛出异常

程序员文章站 2022-05-11 22:43:14
...
PHP代码
<?php
 
/**
 * 错误异常处理
 */
 
$arr = [
     
    'data' => 'hello world',
];
 
 
$res = '123';
 
printData(check($res));
 
printData(check($arr));
 
 
/**
 * Array
(
[line] => 21
[file] => 21
[msg] => not is array
)
Array
(
[data] => hello world
)
 *
 */
 
function check($x){
 
    try{
        if(!is_array($x)) {
 
            throw new Exception('not is array');
        }
 
    }catch(Exception $e){
 
        $data['line'] = $e->getLine();
        $data['file'] = $e->getLine();
        $data['msg'] = $e->getMessage();
        return $data;
    }
 
    return $x;
}
 
$item = '123';
 
$row = [
    '0'=>1,
];
 
 
print_r(checkString($item));
 
print_r(checkString($row));
 
/*
 * Fatal error:  Uncaught Exception: 不是字符串 in D:\xampp\htdocs\phperror.php:77
Stack trace:
#0 D:\xampp\htdocs\phperror.php(62): checkString(Array)
#1 {main}
  thrown in D:\xampp\htdocs\phperror.php on line 82
 
 
Array
(
    [0] => 1
)
 */
 
function checkString($y){
 
    if(!is_string($y)){
 
        throw new Exception('不是字符串');
    }
 
    return $y;
 
}
 
 
function printData($data){
 
    echo '<pre>';
 
    print_r($data);
}
相关标签: php