首頁  >  問答  >  主體

PHP 拋出異常 vs true or false

$edit //一段数据库操作

if ($edit) {
            return redirect('back/label/index')->with('message', '修改成功');
} else {
            return redirect('back/label/index')->with('message', '修改失败');
}
<?php  
//创建可抛出一个异常的函数  
function checkNum($number)  
 {  
 if($number>1)  
  {  
  throw new Exception("Value must be 1 or below");  
  }  
 return true;  
 }  

//在 "try" 代码块中触发异常  
try  
 {  
 checkNum(2);  
 //If the exception is thrown, this text will not be shown  
 echo 'If you see this, the number is 1 or below';  
 }  

//捕获异常  
catch(**Exception $e**)  
 {  
 echo 'Message: ' .$e->getMessage();  
 }  
?>  

希望大神能講下兩種的差別,以及各自的好處,謝謝。

仅有的幸福仅有的幸福2683 天前446

全部回覆(3)我來回復

  • 仅有的幸福

    仅有的幸福2017-05-16 13:07:02

    ifelse: 較為直覺 適合邏輯較為簡單的處理

    異常:更靈活 適合邏輯複雜 層次較多的處理

    我自己平常一般會使用異常來做的

    回覆
    0
  • 習慣沉默

    習慣沉默2017-05-16 13:07:02

    第一種適合簡單的交互,只要告訴使用者失敗/成功。第二種自己調試用的多,能夠看到更多錯誤的原因。

    回覆
    0
  • 迷茫

    迷茫2017-05-16 13:07:02

    因為你在封裝一個功能,用異常可以更優雅地回傳更多錯誤訊息。不要污,要優雅(手動斜眼

    回覆
    0
  • 取消回覆