Exception handling in php

What is Exception in PHP

The exception is an unexpected result from your program. PHP exceptions like other Programing languages can be thrown and catch.

How to handling exception in PHP

PHP has a lot of way to handling exception

  1. Try and catch
  2. Throw exception

Try and catch example

The Following example discuss the try-catch handling in PHP

<?php
//increment function with an exception
function increment($number) {
  if($number<0) {
    throw new Exception("Number must be 1 or more");
  }
  return $number++;
}

// "try" block
try {
  # if the number > zero echo  
  echo increment(-2);
}

//catch exception
catch(Exception $e) {
  echo '\n Message: ' .$e->getMessage();
  echo '\n Error Line: ' .$e->getLine();
} 

Exception Class have a lot of function that you can use   

  • getMessage() − get text message of exception

  • getLine() − get the line number
  • getCode() − get the code of exception

  • getFile() − get the filename

 

Throw exception example

The Following example discuss throw exception handling in PHP

<?php
//increment function with an exception
function increment($number) {
  if($number<0) {
    throw new Exception("Number must be 1 or more");
  }
  return $number++;
}

// "try" block
try {
  # if the number > zero echo  
  echo increment(-2);
}

//catch exception
catch(Exception $e) {
  echo '\n Message: ' .$e->getMessage();
  echo '\n Error Line: ' .$e->getLine();
} 

any time you can change the throw exception message, just by writing your own message

..
  if($number<0) {
    throw new Exception("any message here");
  }
..

you can make your own exception and override the Exception class

class myException extends Exception{
  protected $message = "error message from myException";
}

The Following example discuss how to override exception class in PHP

<?php
class myException extends Exception{
  protected $message = "error message from myException";
}

//increment function with an exception
function increment($number) {
  if($number<0) {
    throw new myException;
  }
  return $number++;
}

// "try" block
try {
  # if the number > zero echo
  echo increment(-2);
}

//catch exception
catch(Exception $e) {
  echo '\n Message: ' .$e->getMessage();
  echo '\n Error Line: ' .$e->getLine();
}