I would like to quote my Java teacher here: exception are for exceptionnal cases. You want to use them when the piece of code you're writing cannot make a decision based on the current situation. Then you throw an exception to delegate that decision to the calling class and so on...
If the code can handle the situation at hand, for instance by returning a value indicating the error, then it should not throw an exception.
Here's an example:
functionget_user(string$email){$stmt=get_connection()->prepare("select * from users where email=:email");// the DB is unreachable, // we don't know what to do,// we bail!if(false===$stmt){thrownew\RuntimeException("Unable to connect to DB");}// the query execution failed,// it happens, // we return false to indicate failureif(!$stmt->execute([':email'=>$email]){returnfalse;}$user=$stmt->fetch();// no user found,// it happens,// we return null to indicate the user // was not foundif(is_null($user)){returnnull;}// everything went fine,// we return the user!returnnewUser($user);}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Nice article.
I would like to quote my Java teacher here: exception are for exceptionnal cases. You want to use them when the piece of code you're writing cannot make a decision based on the current situation. Then you throw an exception to delegate that decision to the calling class and so on...
If the code can handle the situation at hand, for instance by returning a value indicating the error, then it should not throw an exception.
Here's an example: