Error and Exception Handling in PHP

Last updated on May 31 2022
Aridam Das

Table of Contents

Error & Exception Handling in PHP

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences.

Its very simple in PHP to handle an errors.

Using die() function

While writing your PHP program you should check all possible error condition before going ahead and take appropriate action when required.

Try following example without having /tmp/test.xt file and with this file.

<?php   
if(!file_exists("/tmp/test.txt")) 
{      die("File not found");   
}
else 
{      
$file = fopen("/tmp/test.txt","r");      
print "Opend file sucessfully";   
}   
// Test of the code here.
?>

This way you can write an efficient code. Using above technique you can stop your program whenever it errors out and display more meaningful and user friendly message.

Defining Custom Error Handling Function

You can write your own function to handling any error. PHP provides you a framework to define error handling function.

This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context) −

Syntax

error_function(error_level,error_message, error_file,error_line,error_context);

Sr.No Parameter & Description
1 error_level

Required – Specifies the error report level for the user-defined error. Must be a value number.

2 error_message

Required – Specifies the error message for the user-defined error

3 error_file

Optional – Specifies the file name in which the error occurred

4 error_line

Optional – Specifies the line number in which the error occurred

5 error_context

Optional – Specifies an array containing every variable and their values in use when the error occurred

Possible Error levels

These error report levels are the different types of error the user-defined error handler can be used for. These values cab used in combination using | operator

Sr.No Constant & Description Value
1 .E_ERROR

Fatal run-time errors. Execution of the script is halted

1
2 E_WARNING

Non-fatal run-time errors. Execution of the script is not halted

2
3 E_PARSE

Compile-time parse errors. Parse errors should only be generated by the parser.

4
4 E_NOTICE

Run-time notices. The script found something that might be an error, but could also happen when running a script normally

8
5 E_CORE_ERROR

Fatal errors that occur during PHP’s initial start-up.

16
6 E_CORE_WARNING

Non-fatal run-time errors. This occurs during PHP’s initial start-up.

32
7 E_USER_ERROR

Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()

256
8 E_USER_WARNING

Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()

512
9 E_USER_NOTICE

User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()

1024
10 E_STRICT

Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.

2048
11 E_RECOVERABLE_ERROR

Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())

4096
12 E_ALL

All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)

8191

All the above error level can be set using following PHP built-in library function where level cab be any of the value defined in above table.

int error_reporting ( [int $level] )

Following is the way you can create one error handling function −

<?php   
function handleError($errno, $errstr,$error_file,$error_line) 
{      
echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";      
echo "<br />";      
echo "Terminating PHP Script";            
die();   
}
?>

Once you define your custom error handler you need to set it using PHP built-in library set_error_handler function. Now lets examine our example by calling a function which does not exist.

<?php   
error_reporting( E_ERROR );      
function handleError($errno, $errstr,$error_file,$error_line)
{      
echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";     
echo "<br />";      
echo "Terminating PHP Script";            
die();   }      
//set error handler   
set_error_handler("handleError");     
//trigger error   
myFunction();
?>

Exceptions Handling

PHP 5 has an exception model similar to that of other programming languages. Exceptions are important and provides a better control over error handling.

Lets explain there new keyword related to exceptions.

  • Try − A function using an exception should be in a “try” block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is “thrown”.
  • Throw − This is how you trigger an exception. Each “throw” must have at least one “catch”.
  • Catch − A “catch” block retrieves an exception and creates an object containing the exception information.

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …

  • An exception can be thrown, and caught (“catched”) within PHP. Code may be surrounded in a try block.
  • Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions.
  • Exceptions can be thrown (or re-thrown) within a catch block.

Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php  
try 
{      
$error = 'Always throw this error';     
throw new Exception($error);            
// Code following an exception is not executed.     
 echo 'Never executed';   }catch (Exception $e)
{     
echo 'Caught exception: ',  $e->getMessage(), "\n";   
}      
// Continue execution   
echo 'Hello World';
?>

In the above example $e->getMessage function is used to get error message. There are following functions which can be used from Exception class.

  • getMessage() − message of exception
  • getCode() − code of exception
  • getFile() − source filename
  • getLine() − source line
  • getTrace() − n array of the backtrace()
  • getTraceAsString() − formated string of trace

Creating Custom Exception Handler

You can define your own custom exception handler. Use following function to set a user-defined exception handler function.

string set_exception_handler ( callback $exception_handler )

Here exception_handler is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler().

Example

<?php   
function exception_handler($exception) 
{      
echo "Uncaught exception: " , $exception->getMessage(), "\n";  
}                 
set_exception_handler('exception_handler');   
throw new Exception('Uncaught Exception');      
echo "Not Executed\n";
?>

Check complete set of error handling functions at PHP Error Handling Functions

PHP – Bugs Debugging

Programs rarely work correctly the first time. Many things can go wrong in your program that cause the PHP interpreter to generate an error message. You have a choice about where those error messages go. The messages can be sent along with other program output to the web browser. They can also be included in the web server error log.

To make error messages display in the browser, set the display_errors configuration directive to On. To send errors to the web server error log, set log_errors to On. You can set them both to On if you want error messages in both places.

PHP defines some constants you can use to set the value of error_reporting such that only errors of certain types get reported: E_ALL (for all errors except strict notices), E_PARSE (parse errors), E_ERROR (fatal errors), E_WARNING (warnings), E_NOTICE (notices), and E_STRICT (strict notices).

While writing your PHP program, it is a good idea to use PHP-aware editors like BBEdit or Emacs. One of the special special features of these editors is syntax highlighting. It changes the color of different parts of your program based on what those parts are. For example, strings are pink, keywords such as if and while are blue, comments are grey, and variables are black.

Another feature is quote and bracket matching, which helps to make sure that your quotes and brackets are balanced. When you type a closing delimiter such as }, the editor highlights the opening { that it matches.

There are following points which need to be verified while debugging your program.

  • Missing Semicolons − Every PHP statement ends with a semicolon (;). PHP doesn’t stop reading a statement until it reaches a semicolon. If you leave out the semicolon at the end of a line, PHP continues reading the statement on the following line.
  • Not Enough Equal Signs − When you ask whether two values are equal in a comparison statement, you need two equal signs (==). Using one equal sign is a common mistake.
  • Misspelled Variable Names − If you misspelled a variable then PHP understands it as a new variable. Remember: To PHP, $test is not the same variable as $Test.
  • Missing Dollar Signs − A missing dollar sign in a variable name is really hard to see, but at least it usually results in an error message so that you know where to look for the problem.
  • Troubling Quotes − You can have too many, too few, or the wrong kind of quotes. So check for a balanced number of quotes.
  • Missing Parentheses and curly brackets − They should always be in pairs.
  • Array Index − All the arrays should start from zero instead of 1.

Moreover, handle all the errors properly and direct all trace messages into system log file so that if any problem happens then it will be logged into system log file and you will be able to debug that problem.

So, this brings us to the end of blog. This Tecklearn ‘Error and Exception Handling in PHP’ blog helps you with commonly asked questions if you are looking out for a job in PHP Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

 

0 responses on "Error and Exception Handling in PHP"

Leave a Message

Your email address will not be published. Required fields are marked *