Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Extending Exceptions
Exception class implements Throwable interface and is base class for all Exception classes, predefined exceptions as well as user defined exceptions. The Exception class defines some final (non-overridable) methods to implement those from Throwable interface, and __toString() method that can be overridden to return a string representation of Exception object.
Exception Class Methods
| Method | Description |
|---|---|
| final public function getMessage() | message of exception |
| final public function getCode() | code of exception |
| final public function getFile() | source filename |
| final public function getLine() | source line |
| final public function getTrace() | an array of the backtrace() |
| final public function getPrevious() | previous exception |
| final public function getTraceAsString() | formatted string of trace |
| public function __toString() | formatted string for display |
If user defined exception class re-defines the constructor, it should call parent::__construct() to ensure all available data has been properly assigned.
Example
Following script defines a custom exception class called myException. This type of exception is thrown if value of $num is less than 0 or greater than 100. The getMessage() method of Exception class returns the error message and getLine() method returns line of code in which exception appears −
<?php
class myException extends Exception{
function message(){
return "error : " . $this->getMessage() . " in line no " . $this->getLine();
}
}
$num=125;
try{
if ($num>100 || $num<0)
throw new myException("$num is invalid number");
else
echo "$num is a valid number";
}
catch (myException $m){
echo $m->message();
}
?>
error : 125 is invalid number in line no 10
Extending with Constructor Override
When overriding the constructor in a custom exception, always call the parent constructor to maintain exception functionality −
<?php
class ValidationException extends Exception{
private $field;
public function __construct($message, $field, $code = 0, $previous = null) {
parent::__construct($message, $code, $previous);
$this->field = $field;
}
public function getField() {
return $this->field;
}
}
try {
throw new ValidationException("Invalid email format", "email");
} catch (ValidationException $e) {
echo "Error in field '" . $e->getField() . "': " . $e->getMessage();
}
?>
Error in field 'email': Invalid email format
Conclusion
Extending the Exception class allows you to create custom exceptions with additional properties and methods. Always call parent::__construct() when overriding the constructor to preserve built-in exception functionality.
