Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use a try block to throw exceptions. can't we simply throw and catch them without a try block. What is its importance?

Tags:

php

I am trying to figure out the need of try block in exception handling.

I am learning custom error handling in php and the code is as follows:

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="[email protected]";
    try{
      if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
        throw new customException($email);
      }
    }
    catch(customException $e){
      echo $e->errorMessage();
    }
like image 422
Plo Avatar asked Jun 24 '17 04:06

Plo


1 Answers

The code being executed in the try block may throw different types of exceptions

try {
    thingThatMightBreak();
}
catch (CustomException $e) {
    echo "Caught CustomException ('{$e->getMessage()}')\n{$e}\n";
}
catch (Exception $e) {
    echo "Caught Exception ('{$e->getMessage()}')\n{$e}\n";
}
like image 109
theRemix Avatar answered Oct 14 '22 06:10

theRemix