Home > php教程 > PHP源码 > body text

php抛出异常

PHP中文网
Release: 2016-05-23 08:39:22
Original
1088 people have browsed it

PHP代码

<?php
 
/**
 * 错误异常处理
 */
 
$arr = [
     
    &#39;data&#39; => &#39;hello world&#39;,
];
 
 
$res = &#39;123&#39;;
 
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(&#39;not is array&#39;);
        }
 
    }catch(Exception $e){
 
        $data[&#39;line&#39;] = $e->getLine();
        $data[&#39;file&#39;] = $e->getLine();
        $data[&#39;msg&#39;] = $e->getMessage();
        return $data;
    }
 
    return $x;
}
 
$item = &#39;123&#39;;
 
$row = [
    &#39;0&#39;=>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(&#39;不是字符串&#39;);
    }
 
    return $y;
 
}
 
 
function printData($data){
 
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
 
    print_r($data);
}
Copy after login


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!