Jump to content

[SOLVED] Why use a custom Exception?


ifubad

Recommended Posts

Got the following first custom Exception example from w3schools. The second example is a slightly modified version, that is not using a custom Exception, and outputs exactly the same message, with slightly less code overall. As stated by somewhere explaining why use a custom exception, because "The default exception class doesn't exactly fulfill the graceful part of handling unpredictable results. It just prints out an error message not much different from regular errors."

 

So, what is the big advantage of using a custom exception, if the more graceful message can be printed out within the echo statement of the catch block, when using the default Exception class. To produce cleaner code?

 

Using custom Exception

<?php
class customException extends Exception
  {
  public function errorMessage()
    {
    //error message
    $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
    .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
    return $errorMsg;
    }
  }

$email = "[email protected]";

try
  {
  //check if
  if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
    {
    //throw exception if email is not valid
    throw new customException($email);
    }
  }

catch (customException $e)
  {
  //display custom message
  echo $e->errorMessage();
  }
?>

 

Using default Exception

<?php
$email = "[email protected]";

try
  {
  //check if
  if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
    {
    //throw exception if email is not valid
    throw new Exception($email);
    }
  }

catch (Exception $e)
  {
  //display custom message
  echo 'Error on line '.$e->getLine().' in '.$e->getFile()
    .': <b>'.$e->getMessage().'</b> is not a valid E-Mail address';
  }
?>

Link to comment
https://forums.phpfreaks.com/topic/168362-solved-why-use-a-custom-exception/
Share on other sites

Because (as with any customized class) a customized exception may include mechanisms for logging, emailing admins, all sorts of cool stuff. You may also want to try and catch different types of exceptions. eg;

 

try {
  validate_form();
} catch (envalidNameException $e) {
  // handle invalid name.
} catch (envalidEmailException $e) {
  // handle invalid email.
} catch (envalidPassException $e) {
  // handle invalid password.
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.