我想弄清楚在异常处理中是否需要 try block 。
我正在学习php中的自定义错误处理,代码如下:
class customException extends Exception{
public function errorMessage(){
return "Error at line ".$this->getLine()." in ".$this->getFile()."<br>".$this->getMessage()." is not a valid email address";
}
}
$email="someone@example.com";
try{
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
throw new customException($email);
}
}
catch(customException $e){
echo $e->errorMessage();
}
最佳答案
在try
block 中执行的代码可能会抛出不同类型的异常
try {
thingThatMightBreak();
}
catch (CustomException $e) {
echo "Caught CustomException ('{$e->getMessage()}')\n{$e}\n";
}
catch (Exception $e) {
echo "Caught Exception ('{$e->getMessage()}')\n{$e}\n";
}
关于php - 为什么我们使用 try block 来抛出异常。我们不能在没有 try block 的情况下简单地抛出并捕获它们吗?它的重要性是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44732790/