what is exception?

An exception is a logical/system error that occurs during the normal execution of a script. The exception could either be raised by the system or the program itself it the exception cannot be handled and the caller script/function needs to be informed about the same.


The use of a try…catch block
PHP5 introduces the try…catch block to trap exceptions. Look at the example below.
try { check();}
catch(Exception $e) { echo “Message : ” .$e->getMessage();
echo“Code : ” . $e->getCode();
}
function check() {
if(some error condition) {
throw new Exception(“Error String”,Error Code);
}
}

In the above example, the method check() is called between the try {} block. The try{} block is the area where you will place your code that could raise an exception. Below the try{} block is the catch() {} block. The catch block expects the Exception type of object as a parameter. Within the catch() {} block you will place your logic to either fix the issue or log the error.
In the function check(), we raise an Exception using the ‘throw’ keyword. The statement following ‘throw’ is the syntax of creating a new object of Exception type. The exception class accepts two parameters. The left parameter is a string that is the error message and the right parameter is the integer error code that you wish to assign to that error.
Extending the Exception class

class CustomerException extends Exception {
public function __construct($message = null, $code = 0) {
$t_message = “Exception raised in CustomerException “; $t_message .= “with message : ” . $message;
parent::__construct($t_message, $code);
}
}
function testException() {
throw new CustomerException(“CustomerException has been raised”,101);
}
try { testException(); } catch(CustomerException $e) { echo “Error Message : ” $e->getMessage(); echo “Error Code : ” $e->getCode();}
Output:
Error Message : CustomerException has been raised Error Code : 101





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here