Identify and recover your PHP code from runtime errors with PHP Error Handling techniques. Learn how to handle errors effectively and discover the quick ways to resolve them:
In this tutorial, you will learn PHP coding standards, PHP error types, the die() function, PHP try-catch, debugging, PHP error reporting, and frequently asked questions (FAQs).
Please note that we have used PHP version 7 in all examples.
Let’s begin!
=> In-Depth PHP Tutorials for Beginners
Table of Contents:
PHP Error Handling: Complete Guide

Coding Standards
Following coding standards will improve the quality of the software. Furthermore, it helps to avoid errors.
Some of the coding standards in PHP are listed below:
#1) PHP tags: The use of full PHP tags is preferred over PHP short tags.
#2) Control structures (if, for, foreach, while, switch, etc.)
There should be a single space between the keyword and the opening parenthesis.
#3) Functions
There should be no spaces between:
- The function name and the opening parenthesis.
- The opening parenthesis and the first parameter.
- The parameter (end of the parameter) and the comma.
- The last parameter and the closing parenthesis.
#4) Comments: Use of C++ style comments (// for single-line comments, /* */ for multiline comments) are preferred over shell-style comments (#).
#5) Statements per line: Usually, there should be only a single statement per line.
#6) Code indentation and line length: Using an indent of four spaces (without tabs) is preferred. For better readability of the code, you may limit code lines to 75-85 characters long. Furthermore, code blocks (including curly braces) should be properly aligned.
=>> Visit this link to find the full detailed list.
PHP Error Types
PHP errors can be categorized into three categories. They are,
- Syntax errors
- Logical errors
- Run-time errors
Let’s discuss each of them.
#1) Syntax Errors
A syntax error is an error in the syntax, such as a change in a symbol or a missing symbol, or an extra symbol. It stops the execution of the script. Syntax errors are also known as parse errors.
Examples:
- Missing a closing or opening parentheses
- Extra parentheses
- Missing quotes
- Missing a semicolon
#2) Run-time Errors
A run-time error occurs during the execution of the script. It stops the execution of the script. Run-time errors are also known as exceptions.
Example:
Calling an undefined function or class
##) Logical Errors
A logical error occurs when you make a mistake when expressing something logically. They are difficult to track.
Example:
<?php
if ($n = 1) {
echo "Hello World!";
}
?>
Even though the above example works perfectly and outputs Hello World!, it is not what the user expected to do.
The solution will be something similar to below:
<?php
$n = 1;
if ($n == 1) {
echo "Hello World!";
}
?>
The Die Function
The die() function is equivalent to the exit() function. The die() function is used to output a message and exit from the current script. There is no return value.
The syntax is shown below:
die(message);
The parameter we can pass to the die() function is the message, and it is optional.
The following example shows how to use the die() function:
<?php
$file = "/path/non-existent-file";
$fileOpen = fopen($file, 'r')
or die("Cannot open the file!");
?>
Output:
Warning: fopen(/path/non-existent-file): failed to open stream: No such file or directory in C:\laragon\www\index.php on line 5 Cannot open the file!
PHP Try Catch
PHP has an exception model that can be thrown and caught within PHP. It is popularly known as PHP Try Catch. Also, it is the primary method of handling exceptions/errors in PHP.
- try: A try block contains a block of code that may throw an exception. Each try must have a minimum of one corresponding catch block or finally block.
- catch: A catch block contains a block of code that catch and handle the exception thrown by the try block.
- throw: Each throw must have a minimum of one corresponding catch block.
Syntax:
try {
//write your code here
}
catch (Exception $e) {
//exception handling code
}
finally {
//this code always run (optional)
}
Examples of PHP Try Catch
Let’s see a few examples of PHP try catch.
#1) Simple Exception Handling
<?php
//a function (to check the value is greater than or equal to 100) with an exception
function checkValue($val){
if ($val >= 100) {
throw new Exception('Value must be lower than 100.');
}
return true;
}
//trigger exception within a try block
try {
checkValue(101);
//if an exception is not thrown
echo "Value is lower than 100.";
}
//catch exception
catch (Exception $e) {
echo "Exception: ", $e->getMessage();
}
?>
Output:
Exception: Value must be lower than 100.
#2) Exception handling with a finally block
<?php
function inverse($num) {
if (!$num) {
throw new Exception('Division by zero.');
}
return 1/$num;
}
try {
echo inverse(0)."<br>";
} catch (Exception $e) {
echo "Exception: ", $e->getMessage()."<br>";
//finally
} finally {
echo "Finally. <br>";
}
// continue execution
echo "Happy coding!";
?>
Output:
Exception: Division by zero. Finally. Happy coding!
#3) Exception handling with finally blocks
<?php
function inverse($num) {
if (!$num) {
throw new Exception('Division by zero.');
}
return 1/$num;
}
try {
echo inverse(0)."<br>";
} catch (Exception $e) {
echo "Exception: ", $e->getMessage()."<br>";
//first finally
} finally {
echo "First finally. <br>";
}
try {
echo inverse(4)."<br>";
} catch (Exception $e) {
echo "Exception: ", $e->getMessage()."<br>";
//second finally
} finally {
echo "Second finally. <br>";
}
// continue execution
echo "Happy coding!";
?>
Output:
Exception: Division by zero. First finally. 0.25 Second finally. Happy coding!
What is Debugging
Developers may commit mistakes/errors while coding, and these mistakes/errors are popularly known as bugs.
Debugging is the process of identifying, analyzing, and fixing existing and potential errors. It is a routine process in software development.
Useful Functions for Debugging
The var_dump() and print_r() functions are two popular built-in functions that can be used for debugging in PHP.
#1) var_dump() – The var_dump() function outputs structured information about a variable. It outputs both the type and the value of a variable.
Example:
<?php
$name = "John Doe";
var_dump($name);
?>
Output:
string(8) "John Doe"
#2) print_r() – The print_r () function outputs information about a variable in a human-readable way.
Example:
<?php
$colors = array("red","yellow","green","blue");
print_r($colors);
?>
Output:
Array ( [0] => red [1] => yellow [2] => green [3] => blue )
Free Debugger Extensions
You can use the following debuggers for debugging in PHP. They are free debugger extensions.
PHP Error Reporting
The error_reporting() function is used to report errors in PHP.
Syntax:
error_reporting(level);
The parameter we can pass to the error_reporting() function is the error-report level for the current script, and it is optional.
The usage of error reporting is shown below:
<?php
//report all errors
error_reporting(E_ALL);
//same as error_reporting(E_ALL)
ini_set('error_reporting', E_ALL);
//report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
//report all PHP errors
error_reporting(-1);
//disable or turn off error reporting
error_reporting(0);
?>
Frequently Asked Questions
1. What is PHP try-catch?
PHP try-catch is a method of handling exceptions/errors in PHP.
2. What are PHP Error Handling keywords?
PHP error-handling keywords are try, catch, throw, and finally.
3. Does a syntax error stop the execution of the code?
Yes, it stops the execution of the code.
4. How do I turn off PHP error reporting?
Set the value of error_reporting to zero as shown below to disable or turn off error reporting.
error_reporting(0);
5. Where can I run my PHP code online?
There are several PHP online compilers available, such as PHP Sandbox. Further, they may act as PHP syntax checkers.
Conclusion
Following industrial standards will improve the quality of the software and also help to prevent errors.
PHP errors can be categorized into three categories called syntax errors, logical errors, and run-time errors. The die() function is equivalent to the exit() function, and it is used to output a message and exit from the current script.
PHP try-catch is the primary method of handling exceptions/errors in PHP. Bugs are mistakes/errors committed by developers, while coding and debugging are the processes of identifying, analyzing, and fixing existing and potential errors. The error_reporting() function is used to report errors in PHP.
PREV Tutorial | FIRST Tutorial






