WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP Exception Handling


Exceptions are utilized to change the ordinary stream of a content if a determined blunder occurs.


What is an Exception

With PHP 5 came another item situated method for managing errors.

Exception dealing with is utilized to change the ordinary stream of the code execution if a predefined mistake (extraordinary) condition happens. This condition is called an exception.

This is the thing that ordinarily happens when an exemption is triggered:

  • The current code state is saved
  • The code execution will change to a predefined (custom) special case handler function
  • Depending on the circumstance, the handler may then resume the execution from the spared code state, end the content execution or proceed with the content from an alternate area in the code

We will indicate diverse blunder taking care of methods:

  • Basic utilization of Exceptions
  • Creating a custom special case handler
  • Multiple exceptions
  • Re-tossing an exception
  • Setting a best dimension special case handler

Note: Exceptions should just be utilized with mistake conditions, and ought not be utilized to bounce to somewhere else in the code at a predetermined point.


Basic Use of Exceptions

When a special case is tossed, the code tailing it won't be executed, and PHP will attempt to locate the coordinating "catch" block.

If a special case isn't gotten, a lethal mistake will be issued with a "Uncaught Exception" message.

Lets endeavor to toss an exemption without getting it:

<?php
/make work with an exception
work checkNum($number) {
  if($number>1) {
    throw new Exception("Value must be 1 or below");
  }
  return true;
}

/trigger exception
checkNum(2);
?>

The code above will get a mistake like this:

Fatal error: Uncaught exemption 'Exception'
with message 'Esteem must be 1 or underneath' in C:\webfolder\test.php:6
Stack follow: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} tossed in C:\webfolder\test.php on line 6

Try, toss and catch

To dodge the mistake from the precedent above, we have to make the best possible code to deal with an exemption.

Proper exemption code ought to include:

  1. Try - A capacity utilizing an exemption ought to be in a "try" square. In the event that the special case does not trigger, the code will proceed as typical. Be that as it may if the special case triggers, an exemption is "thrown"
  2. Throw - This is the means by which you trigger an exemption. Each "throw" must have at least one "catch"
  3. Catch - A "catch" square recovers an exemption and makes an article containing the exemption information

Lets endeavor to trigger a special case with legitimate code:

<?php
/make work with an exception
work checkNum($number) {
  if($number>1) {
    throw new Exception("Value must be 1 or below");
  }
  return true;
}

/trigger special case in a "try" block
try {
  checkNum(2);
  //If the special case is tossed, this content won't be shown
  echo 'On the off chance that you see this, the number is 1 or below';
}

//catch exception
catch(Exception $e) {
  echo 'Message: ' .$e->getMessage();
}
?>

The code above will get a blunder like this:

Message: Value must be 1 or underneath

Example explained:

The code above tosses a special case and gets it:

  1. The checkNum() work is made. It checks if a number is more prominent than 1. On the off chance that it is, a special case is thrown
  2. The checkNum() work is brought in a "try" block
  3. The special case inside the checkNum() work is thrown
  4. The "catch" square recovers the special case and makes an article ($e) containing the exemption information
  5. The mistake message from the special case is reverberated by calling $e->getMessage() from the exemption object

However, one approach to get around the "every toss must have a catch" rule is to set a best dimension exemption handler to deal with mistakes that slip through.


Creating a Custom Exception Class

To make a custom exemption handler you should make an extraordinary class with capacities that can be considered when a special case happens in PHP. The class must be an augmentation of the exemption class.

The custom special case class acquires the properties from PHP's special case class and you can add custom capacities to it.

Lets make a special case class:

<?php
class customException expands Exception {
  public work errorMessage() {
    //mistake message
    $errorMsg = 'Mistake on line '.$this->getLine().' in '.$this->getFile()
    .': <b>'.$this->getMessage().'</b> is definitely not a legitimate E-Mail address';
    return $errorMsg;
  }
}

$email = "someone@example...com";

try {
  //check if
  if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
    //toss exemption if email isn't valid
    throw new customException($email);
  }
}

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

The new class is a duplicate of the old exemption class with an expansion of the errorMessage() work. Since it is a duplicate of the old class, and it acquires the properties and strategies from the old class, we can utilize the special case class strategies like getLine() and getFile() and getMessage().

Example explained:

The code above tosses a special case and gets it with a custom exemption class:

  1. The customException() class is made as an expansion of the old special case class. Thusly it acquires all techniques and properties from the old special case class
  2. The errorMessage() work is made. This capacity restores a blunder message if an email address is invalid
  3. The $email variable is set to a string that is definitely not a legitimate email address
  4. The "try" square is executed and a special case is tossed since the email address is invalid
  5. The "catch" square gets the special case and shows the mistake message

Multiple Exceptions

It is feasible for a content to utilize numerous exemptions to check for various conditions.

It is conceivable to utilize a few if..else hinders, a switch, or home different special cases. These special cases can utilize distinctive exemption classes and return diverse blunder messages:

<?php
class customException broadens Exception {
  open capacity errorMessage() {
    /mistake message
    $errorMsg = 'Mistake on line '.$this->getLine().' in '.$this->getFile()
    .': <b>'.$this->getMessage().'</b> is certifiably not a substantial E-Mail address';
    return $errorMsg;
  }
}

$email = "someone@example.com";

try {
  //check if
  if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
    //toss exemption if email isn't valid
    throw new customException($email);
  }
  //check for "example" in mail address
  if(strpos($email, "example") !== FALSE) {
    throw new Exception("$email is a model e-mail");
  }
}

get (customException $e) {
  echo $e->errorMessage();
}

catch(Exception $e) {
  echo $e->getMessage();
}
?>

Example explained:

The code above tests two conditions and tosses a special case if any of the conditions are not met:

  1. The customException() class is made as an expansion of the old special case class. Thusly it acquires all strategies and properties from the old exemption class
  2. The errorMessage() work is made. This capacity restores a mistake message if an email address is invalid
  3. The $email variable is set to a string that is a substantial email address, yet contains the string "example"
  4. The "try" square is executed and a special case isn't tossed on the first condition
  5. The second condition triggers an exemption since the email contains the string "example"
  6. The "catch" square gets the exemption and presentations the right blunder message

If the special case tossed were of the class customException and there were no customException get, just the base special case get, the special case would be taken care of there.


Re-tossing Exceptions

Sometimes, when a special case is tossed, you may wish to deal with it uniquely in contrast to the standard way. It is conceivable to toss a special case a second time inside a "catch" block.

A content should conceal framework mistakes from clients. Framework blunders might be essential for the coder, however are of no enthusiasm to the client. To make things simpler for the client you can re-toss the special case with an easy to use message:

<?php
class customException expands Exception {
  public work errorMessage() {
    //mistake message
    $errorMsg = $this->getMessage().' is certifiably not a legitimate E-Mail address.';
    return $errorMsg;
  }
}

$email = "someone@example.com";

try {
  try {
    //check for "example" in mail address
    if(strpos($email, "example") !== FALSE) {
      //toss exemption if email isn't valid
      throw new Exception($email);
    }
  }
  catch(Exception $e) {
    //re-toss exception
    throw new customException($email);
  }
}

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

Example explained:

The code above tests if the email-address contains the string "example" in it, on the off chance that it does, the special case is re-thrown:

  1. The customException() class is made as an expansion of the old special case class. Along these lines it acquires all techniques and properties from the old special case class
  2. The errorMessage() work is made. This capacity restores a blunder message if an email address is invalid
  3. The $email variable is set to a string that is a legitimate email address, however contains the string "example"
  4. The "try" square contains another "try" square to make it conceivable to re-toss the exception
  5. The exemption is activated since the email contains the string "example"
  6. The "catch" square gets the special case and re-tosses a "customException"
  7. The "customException" is gotten and shows a mistake message

If the special case isn't gotten in its ebb and flow "attempt" square, it will look for a catch hinder on "higher levels".


Set a Top Level Exception Handler

The set_exception_handler() work sets a client characterized capacity to deal with all uncaught special cases.

<?php
work myException($exception) {
  reverberation "<b>Exception:</b> " . $exception->getMessage();
}

set_exception_handler('myException');

toss new Exception('Uncaught Exception occurred');
?>

The yield of the code above ought to be something like this:

Exception: Uncaught Exception happened

In the code above there was no "catch" square. Rather, the best dimension exemption handler activated. This capacity ought to be utilized to get uncaught exceptions.


Rules for exceptions

  • Code might be encompassed in an attempt hinder, to help get potential exceptions
  • Each attempt square or "throw" must have something like one comparing get block
  • Multiple get squares can be utilized to get diverse classes of exceptions
  • Exceptions can be tossed (or re-tossed) in a catch hinder inside an attempt block

A basic standard: If you toss something, you need to get it.