throw 抛异常
throw new Exception(‘参数只能是数字‘)
try...catch 异常
try {
//抛异常的代码
} catch (Exception $e) {
echo $e->getMessage();
}
实例
/src/TestException.php (抛异常)
<?php
namespace Huyongjian\Php;
use Exception;
class TestException{
//测试方法
public function add($num, $num2){
if(!is_numeric($num) || !is_numeric($num2)){
throw new Exception(‘参数只能是数字‘);
}
return $num + $num2;
}
}
/index.php (获取异常)
<?php
require "./vendor/autoload.php";
use Huyongjian\Php\TestException;
try {
$testException = new TestException();
$testException->add(‘error‘, 3);
} catch (Exception $e) {
echo $e->getMessage();
}
浏览器测试