PHP throws exception vs true or false
仅有的幸福
仅有的幸福 2017-05-16 13:05:02
0
3
476
  • Use Boolean for logical processing.

$edit //A database operation

if ($edit) {
            return redirect('back/label/index')->with('message', 'Modification successful');
} else {
            return redirect('back/label/index')->with('message', 'Modification failed');
}
  • PHP exception handling, code source

<?php
//Create a function that can throw an exception
function checkNum($number)
 {
 if($number>1)
  {
  throw new Exception("Value must be 1 or below");
  }
 return true;
 }

//Trigger exception in "try" code block
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
catch(**Exception $e**)
 {
 echo 'Message: ' .$e->getMessage();
 }
?> 

I hope someone can explain the difference between the two and their respective benefits, thank you.

仅有的幸福
仅有的幸福

reply all(3)
仅有的幸福

ifelse: more intuitive and suitable for processing with simpler logic

Exception: more flexible, suitable for processing with complex logic and multiple levels

I usually use exceptions to do this

習慣沉默

The first one is suitable for simple interactions, just tell the user failure/success. The second type is used more often for self-debugging, and you can see more causes of errors.

迷茫

Because you are encapsulating a function, using exceptions can return more error information more elegantly. Don’t be dirty, be elegant (manual squinting

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template