Error Handling is very important part of any programming language. It enables developers to handle mistakes in a very effective manner, giving users insightful feedback and preserving the application’s stability. In this article, we will learn about type of errors and also PHP error handling with the help of examples.
When we write any wrong syntax or wrong code, then error comes. It is a type of mistake. PHP contains basically four types of errors.
- Syntax Errors (Parse Errors)
- Fatal Errors
- Warning Errors
- Notice Errors
Syntax Errors (Parse Errors)
When we write any wrong syntax, then this types of error occurs. For example, missing semicolon, missing dollar before variable, Extra parentheses etc. It is also known as Parsed Error. It is caught by compiler. It stops execution of script.
Example
$var1 = "Desktop"; $var2 = "Mobile" $var3 = "Tablet";
Answer will be:
Parse error: syntax error, unexpected ‘$var3’ (T_VARIABLE) in error_handling.php on line 5
Fatal Errors
This type of error comes generally, when we call an undefined function OR when we make object of an non-existing class. It is very critical error an stop execution of script.
Example
function addition($var1, $var2) { $var3 = $var1 + $var2; return $var3; } $a = 10; $b = 5; echo subtract($a, $b);
Answer will be:
Fatal error: Uncaught Error: Call to undefined function subtract() in error_handling.php:11 Stack trace: #0 {main} thrown in error_handling.php on line 11
Warning Errors
This type of error comes generally, when we missed any file to include OR passed wrong number of parameters to a function. It will not stop the script execution. It is a non-critical error.
Example
echo 10/0;
Answer will be:
INF
PHP Warning: Division by zero in error_reporting.php on line 3
include('connection.php'); $a = 10; $b = 20; $c = $a + $b; echo "The value of c is: ".$c;
Answer will be:
The value of c is: 30
PHP Warning: include(connection.php): failed to open stream: No such file or directory in error_reporting.php on line 3
Also read about File Handing using PHP
Notice Errors
This error is same as warning error. It does not stop script execution. It is also non-critical error. It comes generally, when we used any variable without define them.
Example
$a = 10; $b = 20; $d = $a + $b; echo "The value of c is: ".$c."\n"; echo "The value of d is: ".$d;
Answer will be:
The value of c is:
The value of d is: 30
PHP Notice: Undefined variable: c in error_reporting.php on line 7
Error handling is a key point of any application. Every developers keeps their application free of errors, which enhance user experience and application reliability. Developing robust and secure PHP applications requires efficient error handling.