Exception in PHP

Posted on Updated on

What is an Exception?

With PHP 5 came another item situated method for managing blunders. Exemption taking care of is utilized to change the ordinary stream of the code execution if a predetermined mistake (excellent) condition happens. This condition is called a special case.

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

The present code state is spared

The code execution will change to a predefined (custom) special case handler capacity. Contingent upon the circumstance, the handler might then resume the execution from the spared code state, end the script execution or proceed with the script from an alternate area in the code.

We will demonstrate diverse mistake taking care of systems:

  • Fundamental utilization of Exceptions
  • Making a custom exemption handler
  • Different special cases
  • Re-tossing an exemption
  • Setting a top level exemption handler

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

Essential Use of Exceptions

At the point when a special case is tossed, the code tailing it won’t be executed, and PHP will attempt to locate the coordinating “catch” piece.

In the event that an exemption is not got, a deadly blunder will be issued with an “Uncaught Exception” message.

Lets attempt to toss a special case without getting it:

<?php

/make capacity with a special case

capacity checkNum($number) {

if($number>1) {

toss new Exception(“Value must be 1 or underneath”);

}

return genuine;

}

/trigger special case

checkNum(2);

?>

The code above will get a blunder like this:

Lethal mistake: Uncaught exemption “Special case” with message ‘Quality must be 1 or beneath’ 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

Attempt, toss and get

To maintain a strategic distance from the mistake from the sample above, we have to make the best possible code to handle an exemption.

Legitimate special case code ought to include:

Attempt – A capacity utilizing an exemption ought to be as a part of an “attempt” square. On the off chance that the exemption does not trigger, the code will proceed as ordinary. However in the event that the special case triggers, an exemption is “tossed”.

Toss – This is the manner by which you trigger a special case. Every “toss” must have no less than one “catch”

Get – A “catch” piece recovers a special case and makes an item containing the exemption data.

Lets attempt to trigger a special case with legitimate code:

<?php

/make capacity with a special case

capacity checkNum($number) {

if($number>1) {

toss new Exception(“Value must be 1 or underneath”);

}

return genuine;

}

/trigger special case in an “attempt” square

attempt {

checkNum(2);

/If the special case is tossed, this content won’t be appeared

reverberation ‘In the event that you see this, the number is 1 or beneath’;

}

/get special case

catch(Exception $e) {

reverberation ‘Message: ” .$e->getMessage();

}

?>

The code above will get a blunder like this:

Message: Value must be 1 or beneath

Sample clarified:

The code above tosses an exemption and gets it:

The checkNum() capacity is made. It checks if a number is more prominent than 1. On the off chance that it is, a special case is tossed The checkNum() capacity is brought in an “attempt” square.

The exemption inside of the checkNum() capacity is tossed.

The “catch” square recovers the special case and makes an item ($e) containing the exemption data.

The mistake message from the special case is resounded by calling $e->getMessage() from the exemption object.

On the other hand, one approach to get around the “each toss must have a catch” guideline is to set a top level special case handler to handle blunders that sneak past.

Making a Custom Exception Class

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

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

Lets make a special case class:

<?php

class customException augments Exception {

open capacity errorMessage() {

/mistake message

$errorMsg = ‘Mistake on line ‘.$this->getLine().’ in ‘.$this->getFile()

.’: <b>’.$this->getMessage().'</b> is not a substantial E-Mail address’;

return $errorMsg;

}

}

$email = “someone@example…com”;

attempt {

/check if

if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {

/toss special case if email is not substantial

toss new customException($email);

}

}

get (customException $e) {

/show custom message

reverberation $e->errorMessage();

}

?>

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

Sample clarified:

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

The customException() class is made as an augmentation of the old special case class. Along these lines it acquires all systems and properties from the old special case class The errorMessage() capacity is made. This capacity gives back a mistake message if an email location is invalid.

The $email variable is set to a string that is not a substantial email address.

The “attempt” square is executed and a special case is tossed subsequent to the email location is invalid.

The “catch” piece gets the exemption and shows the mistake message.

Various Exceptions

It is feasible for a script to utilize different special cases to check for various conditions.

It is conceivable to utilize a few if..else obstructs, a switch, or settle different special cases.

These special cases can utilize distinctive exemption classes and return diverse mistake messages:

<?php

class customException expands Exception {

open capacity errorMessage() {

/blunder message

$errorMsg = ‘Blunder on line ‘.$this->getLine().’ in ‘.$this->getFile()

.’: <b>’.$this->getMessage().'</b> is not a legitimate E-Mail address’;

return $errorMsg;

}

}

$email = “someone@example.com”;

attempt {

/check if

if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {

/toss special case if email is not legitimate

toss new customException($email);

}

/check for “instance” in mail address

if(strpos($email, “illustration”) !== FALSE) {

toss new Exception(“$email is an illustration email”);

}

}

get (customException $e) {

reverberation $e->errorMessage();

}

catch(Exception $e) {

reverberation $e->getMessage();

}

?>

Illustration Clarified:

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

The customException() class is made as an expansion of the old exemption class. Along these lines it acquires all systems and properties from the old special case class.

The errorMessage() capacity is made. This capacity gives back a blunder message if an email location is invalid.

The $email variable is set to a string that is a substantial email address, however contains the string “case”.

The “attempt” square is executed and a special case is not tossed on the first condition.

The second condition triggers an exemption since the email contains the string “illustration”.

The “catch” square gets the special case and shows the right blunder message.

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

Re-tossing Exceptions

Some of the time, when a special case is tossed, you might wish to handle it uniquely in contrast to the standard way. It is conceivable to toss a special case a second time inside of a “catch” piece. A script ought to conceal framework blunders from clients. Framework blunders might be essential for the coder, yet are of no enthusiasm to the client. To make things less demanding for the client you can re-toss the special case with an easy to use message:

<?php

class customException expands Exception {

open capacity errorMessage() {

/blunder message

$errorMsg = $this->getMessage().’ is not a legitimate E-Mail address.’;

return $errorMsg;

}

}

$email = “someone@example.com”;

attempt {

attempt {

/check for “instance” in mail address

if(strpos($email, “sample”) !== FALSE) {

/toss exemption if email is not substantial

toss new Exception($email);

}

}

catch(Exception $e) {

/re-toss exemption

toss new customException($email);

}

}

get (customException $e) {

/show custom message

reverberation $e->errorMessage();

}

?>

Sample Clarified:

The code above tests if the email-address contains the string “sample” in it, on the off chance that it does, the exemption is re-tossed:

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.

The errorMessage() capacity is made. This capacity gives back a blunder message if an email location is invalid

The $email variable is set to a string that is a legitimate email address, yet contains the string “sample”.

The “attempt” piece contains another “attempt” square to make it conceivable to re-toss the exemption.

The exemption is activated subsequent to the email contains the string “case”.

The “catch” square gets the special case and re-tosses a “customException”.

The “customException” is gotten and shows a mistake message.

On the off chance that the special case is not got in its flow “attempt” piece, it will scan for a catch obstruct on “more elevated amounts”.

Set a Top Level Exception Handler

The set_exception_handler() capacity sets a client characterized capacity to handle all uncaught special cases.

<?php

capacity myException($exception) {

reverberation “<b>Exception:</b> ” . $exception->getMessage();

}

set_exception_handler(‘myException’);

toss new Exception(‘Uncaught Exception happened’);

?>

For more details and queries please feel free to email, visit or call us. Wishing you the very best for all your future endeavors.

Helpline: 9814666333, 8699444666

Email:info@technocampus.co.in

**************************************************************************************************************

Please fill the FORM and we shall contact you soon.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s