PHP Exception Handling

PHP Exception Handling 7Design.Studio

Exception handling is an effective way to handle errors, modern Object oriented extensions use exceptions.

Throw an Exception:

We have to use PHP built-in class “Exception”. To throw an exception with command “throw new Exception()”. Write custom error message between brackets().

throw new Exception('Promo value cannot be less than or equal to zero.');

Try/Catch Block:

Exception will catch by the “catch” block. Each “try” block must have at least one corresponding “catch” block.

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …“.

To throw error message, we call “getMessage()” method. Some other useful methods are, “getFile()“, “getLine()“, “getCode()“, “getTrace()“. These methods provides by Exception class.

<?php
class Promotion{
  public function calculateTotal($productvalue, $promovalue){
    if($promovalue<= 0){
      throw new Exception('Promo value cannot be less than or equal to zero.'); // Throw custom error message
    }
    return $productvalue/$promovalue; // Without exception, we get "Warning: Division by zero".
  }
}

try{ //Try Block handles normal data
  $productpromo = new Promotion();
  echo $productpromo->calculateTotal(20,0);
} catch (Exception $e){ //Catch Block handles exceptions
  echo $e->getMessage(); // Get custom error message
}
?>

Extending Exception: We can extend custom exception using built-in “Exception” class, it is useful to write custom logic on user-defined exceptions.

<?php
	class MyException extends Exception{}

	class Promotion{
		public function calculateTotal($productvalue, $promovalue){
			if($promovalue <= 0){
				throw new Exception('Promo value cannot be less than or equal to zero.');
			} elseif($productvalue <= 0) { throw new MyException('Extends'); // Will Caught } return $productvalue/$promovalue; } } try{ $productpromo = new Promotion(); echo $productpromo->calculateTotal(0,20);
	} catch (MyException $extendException){
		echo $extendException->getLine(); // Return exception line number
	} catch (Exception $e){
		echo $e->getMessage();	
	}
?>

Further reference about Exception:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2018 7Design.Studio | Web Design, Web Application Development & UX Design | Chennai | India

Up ↑