-
Hajipur, Bihar, 844101
In PHP, errors can occur for many reasons, such as invalid input, missing files, or unexpected behavior in the code. Handling errors effectively is crucial for creating stable and reliable applications. One of the most powerful ways to manage errors in PHP is through exceptions. Exceptions allow developers to handle errors gracefully without abruptly stopping the program.
An exception is an object that represents an error or unexpected behavior in your application. When an error occurs, an exception can be “thrown” to indicate that something went wrong. You can then “catch” the exception and handle it in a controlled way.
Using exceptions, you separate normal program logic from error-handling logic, making your code cleaner and easier to maintain.
try-catch
BlockThe basic mechanism for handling exceptions in PHP is the try-catch
block.
try
– Contains code that may throw an exception.
catch
– Contains code to handle the exception if one is thrown.
Example:
try {
$number = 10;
if ($number > 5) {
throw new Exception("Number is too large!");
}
echo "Number is acceptable.";
} catch (Exception $e) {
echo "Caught exception: " . $e->getMessage();
}
Here, the throw
statement creates a new Exception object. The catch
block receives this exception and allows you to respond to it, for example by displaying an error message or logging it.
When you throw an exception, PHP creates an Exception object. This object has useful methods:
getMessage()
– Returns the error message.
getCode()
– Returns the exception code (optional, set when creating the exception).
getFile()
– Returns the file where the exception was thrown.
getLine()
– Returns the line number where the exception was thrown.
getTrace()
– Returns an array representing the stack trace.
getTraceAsString()
– Returns the stack trace as a string.
Example:
try {
throw new Exception("Something went wrong", 101);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "<br>";
echo "Code: " . $e->getCode() . "<br>";
echo "File: " . $e->getFile() . "<br>";
echo "Line: " . $e->getLine() . "<br>";
}
This provides detailed information about the error, which is useful for debugging.
catch
BlocksPHP allows multiple catch
blocks to handle different types of exceptions. This is useful when your code may throw different exceptions and you want to handle each type differently.
Example:
class CustomException extends Exception {}
try {
$value = -1;
if ($value < 0) {
throw new CustomException("Value cannot be negative");
} elseif ($value == 0) {
throw new Exception("Value cannot be zero");
}
} catch (CustomException $ce) {
echo "Custom exception: " . $ce->getMessage();
} catch (Exception $e) {
echo "General exception: " . $e->getMessage();
}
Here, negative values are handled separately from zero values, showing how multiple catch blocks can improve error handling.
finally
BlockPHP also supports a finally
block. Code inside finally
will always execute, whether an exception was thrown or not. This is useful for cleaning up resources, such as closing database connections or files.
Example:
try {
$file = fopen("example.txt", "r");
if (!$file) {
throw new Exception("File cannot be opened");
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
if ($file) {
fclose($file);
echo "File closed.";
}
}
Even if an exception occurs, the file is properly closed in the finally
block.
You can create your own exception classes by extending the built-in Exception
class. This allows you to define specialized exceptions for specific types of errors.
Example:
class DatabaseException extends Exception {}
class FileException extends Exception {}
try {
$dbConnected = false;
if (!$dbConnected) {
throw new DatabaseException("Database connection failed");
}
} catch (DatabaseException $de) {
echo "Database Error: " . $de->getMessage();
} catch (FileException $fe) {
echo "File Error: " . $fe->getMessage();
}
Custom exceptions help organize error handling, especially in larger applications.
Functions and methods can throw exceptions, which allows error handling to be pushed to the calling code.
Example:
function divide($a, $b) {
if ($b == 0) {
throw new Exception("Division by zero is not allowed");
}
return $a / $b;
}
try {
echo divide(10, 0);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
This approach keeps the function clean and delegates error handling to the caller.
PHP exceptions provide a structured way to handle errors, separating normal code from error-handling code. Key points to remember:
Use try-catch
blocks to catch exceptions.
The throw
statement creates an exception object.
Multiple catch blocks allow handling different exceptions separately.
The finally
block ensures cleanup code runs regardless of exceptions.
Custom exception classes help manage specific error types in complex applications.
Functions and methods can throw exceptions, passing error-handling responsibility to the caller.
Using exceptions improves application stability, readability, and makes debugging easier.
Write a PHP script that throws an exception if a variable $age
is less than 18 and catches it to display an error message.
Create a function divide($a, $b)
that throws an exception when dividing by zero. Call the function and handle the exception.
Write a PHP program that opens a file. If the file cannot be opened, throw an exception and catch it, displaying a user-friendly message.
Implement a custom exception class called DatabaseException
. Throw and catch this exception when a simulated database connection fails.
Write a script that uses multiple catch
blocks to handle both a CustomException
and a general Exception
.
Create a PHP function that reads a configuration value from an array. If the key does not exist, throw an exception. Handle the exception gracefully.
Write a PHP program that demonstrates the use of a finally
block to close a database connection or file, whether or not an exception occurs.
Implement a custom exception FileException
for file-related errors and throw it when a file size exceeds a limit. Catch and display a message.
Write a script that validates user input for a number. If the number is negative, throw an exception; if zero, throw another type of exception. Use multiple catch
blocks.
Create a class Calculator
with a method sqrt($number)
that throws an exception if the number is negative. Use a try-catch block to handle this error.