如何处理方法抛出的异常?有必要该方法不会在方法中抛出异常'检查'
<?php
class AllAccidents
{
public static function check() {
try {
$x = 1;
if($x)
throw new Exception("Value must be more than 1");
}catch (Exception $e){
echo "hello>>".$e->getMessage();
}
}
}
class Test
{
public function go(){
try{
AllAccidents::check();
} catch (Exception $e){
}
}
}
$obj = new Test();
$obj->go();
?>
答案 0 :(得分:1)
我已经像这样格式化了你的代码,你可以在想要抛出异常时设置你的逻辑
<?php
class AllAccidents
{
public static function check() {
try {
self::checkNum(2);
}catch (Exception $e){
echo $e->getMessage();
}
}
public static function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
}
class Test
{
public function go(){
try{
AllAccidents::check();
} catch (Exception $e){
}
}
}
$obj = new Test();
$obj->go();
?>