Php Exception Handling Best Practices

In this tutorial you will learn how to handle exception in php , and all php error handling best practices

PHP Error Reporting

Exception handling is implemented to catch any runtime error handle the unwanted termination of the application; it shows some user-friendly error message.

Exception can occur for various reasons; here is few reasons that cause an exception.

  • Wrong input either from user or from other program
  • Wrong data type or casting
  • More data length than accepted or specified
  • Other dependent service failure
  • Disconcertion with database server due any reason
  • Bad coding, where some logical flow was not considered

How to handle exception in php code

In this article you will learn about the different types of errors including error logs, error handling functions, error handling, and some error handling technique provided by PHP framework error handling.

So sometimes we are saying error sometimes exception, is there any difference!

PHP error handling keywords

  • Try

    We write code inside the try block that may potentially throw an exception.

  • Catch

    Inside catch block codes written for handling the exception, so the exception does not terminate the application, also this is the place where we can call all type of error logging methods

  • Throw

    Using throw keyword we can throw the current exception or can throw a new exception with custom message

  • Finally

    Most of the developer don’t write this finally block, this block is always executed whether any exception occur or not, so if you need anything to be executed at last, this is the place to call the method

PHP error handling examples

Let's look at the code below

function checkAge($age) {
$ageInput = number_format($age, 2);
if($ageInput<=18) {
    throw new Exception("Age should 18 or more");
  }
  return true;
}

Above function expect an integer value.
Now we call the above function twice, one with right parameter, second time with wrong parameter, so that cause an error

try catch in Php

try {
checkAge(20); // excuted with no error
checkAge(some_string_value); // this will cause an exception
//If the exception is thrown, this text will not be shown
echo 'Successfully Executed, No Exception';
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
 

All error details either you can log in database or/and for quick notification send an email to developer team

Custom exception handling in Php

Now we create a custom exception class then use that class to catch and throw custom exception in different situation with different try catch block.

<?php
class customException extends Exception {
public function errorMessage() {
//custom error message
$errorMsg = 'Error on line '.$this->getLine().' in File '.$this->getFile()
.' in code : <b>'.$this->getMessage().'</b> ';
	
	
    return $errorMsg;
    }
}?>

We can call the above class in difference exception handling scenario.

Consider following email error handling

<?php
$email = "incorrect email @domain...com";
try {
//check if valid email
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage();
}?>
 
Error Handling in Php
PHP Tutorial

Other Popular Tutorials
PHP Examples | Join PHP Online Course