PHP Extending Exceptions

PHPServer Side ProgrammingProgramming

Introduction

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.

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

Example

 Live Demo

<?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();
}
?>

Output

Run above code with $num=125 and $num=90 to get error message and message of valid number

error : 125 is invalid number in line no 10
raja
Published on 18-Sep-2020 12:12:05
Advertisements