Lectures Notes On Class 23: Exception Handling in PHP
Objective
In this class, students will
learn how to handle exceptions in PHP using the try, catch, and finally blocks.
Additionally, they will learn how to create custom exception classes. By the
end of the session, students will be able to manage errors and exceptions
effectively using structured exception handling and will be able to implement
their custom exception types.
Introduction
to Exceptions
An exception is an event
that occurs during the execution of a program that disrupts the normal flow of
the program’s instructions. Exceptions can be thrown (indicating that an error
occurred) and caught (to handle the error gracefully).
Why Use
Exception Handling?
- Separation
of Error Handling Code: It allows you to separate
normal code from error-handling code, making the code cleaner and more
readable.
- Propagating
Errors: Exceptions can propagate up the call stack
until they are caught, making it easier to manage errors that occur deep
within a function or class.
- Cleaner
Code: Reduces the need for multiple checks and
allows for a more structured way to manage errors.
Basic Syntax
of Exception Handling
In PHP, exceptions are handled
using the following constructs:
1. try: The
block of code that may throw an exception is placed inside the try block.
2. catch: The catch
block is used to handle the exception if it occurs. You can have multiple catch
blocks to handle different types of exceptions.
3. finally: This
block is executed after the try and catch blocks, regardless of whether an
exception was thrown or not. It is often used for cleanup code.
Example
of Exception Handling
Here is a basic example that
demonstrates how to use try, catch, and finally:
php
Copy code
<?php
function divide($num1,
$num2) {
if ($num2 == 0) {
throw new Exception("Division by
zero is not allowed.");
}
return $num1 / $num2;
}
try {
echo divide(10, 0);
} catch (Exception
$e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally
{
echo "This will always
execute.\n";
}
?>
Explanation:
- The divide
function throws an exception if the second parameter is zero.
- The try
block attempts to call the divide function. If an exception is thrown,
control passes to the catch block.
- The catch
block catches the exception and outputs the error message.
- The finally
block executes regardless of whether an exception was thrown or caught.
Creating
Custom Exception Classes
You can create your own exception
classes by extending the built-in Exception class. This allows you to define
additional properties or methods specific to your application.
Example
of a Custom Exception Class
Here’s how to create a custom
exception class in PHP:
php
Copy code
<?php
class MyCustomException
extends Exception {
public function errorMessage() {
// Error message
return 'Error on line ' . $this->getLine()
. ' in ' . $this->getFile() . ': ' . $this->getMessage();
}
}
function testCustomException($value)
{
if ($value < 1) {
throw new MyCustomException("Value
must be greater than zero.");
}
return $value;
}
try {
testCustomException(0);
} catch
(MyCustomException $e) {
echo $e->errorMessage();
}
?>
Explanation:
- The MyCustomException
class extends the base Exception class and includes a method errorMessage()
that formats the error message.
- The testCustomException
function throws a MyCustomException if the provided value is less than
one.
- In
the try block, the testCustomException function is called. If it throws an
exception, the catch block catches it and calls the errorMessage() method
to output the formatted error.
Best
Practices for Exception Handling
1. Use Specific
Exceptions: Instead of catching general exceptions, use
specific exception classes to handle different error scenarios appropriately.
2. Don't Use
Exceptions for Control Flow: Exceptions should be used for
exceptional situations, not regular control flow.
3. Log
Exceptions: Consider logging exceptions to a file or
monitoring system for further analysis and debugging.
4. Clean Up
Resources: Use finally to release resources, such as closing database connections,
to ensure they are freed up regardless of whether an exception occurred.
Conclusion
In this class, students learned
the fundamentals of exception handling in PHP, including the use of try, catch,
and finally blocks, as well as how to create custom exception classes.
Understanding how to manage exceptions effectively is crucial for building
robust and maintainable applications.
Assignment
1. Create a
custom exception class named InvalidAgeException that throws an error when an
invalid age is provided (e.g., a negative number).
2. Implement
a function setAge($age) that throws the InvalidAgeException if the age is
invalid. Test this function using try and catch to handle the exception and
display the error message.
Solutions
1. Create a custom exception class named InvalidAgeException that throws an error when an invalid age is provided (e.g., a negative number).
To create a custom exception class named InvalidAgeException in PHP, follow these steps. This exception will throw an error when an invalid age (such as a negative number) is provided.
Step 1:
Define the Custom Exception Class
You need to create a new class that
extends the built-in Exception class. Here’s how you can define the InvalidAgeException:
<?php
class InvalidAgeException
extends Exception {
// You can customize the constructor to
provide a custom message
public function __construct($message = "Invalid
age provided") {
// Call the parent constructor to
initialize the exception
parent::__construct($message);
}
}
?>
Explanation:
1. Class
Definition: The class InvalidAgeException is defined, extending the built-in Exception
class. This allows it to behave like a standard exception but with custom
behavior.
2. Constructor: The
constructor takes a $message parameter (defaulting to "Invalid age
provided") and passes it to the parent Exception constructor. This allows
you to customize the error message when the exception is thrown.
Step 2:
Use the Custom Exception in a Function
Next, you will write a function
that checks for valid age input and throws the InvalidAgeException when the age
is negative.
<?php
function setAge($age)
{
if ($age < 0) {
// Throw the custom exception if the
age is negative
throw new InvalidAgeException("Age
cannot be negative: $age");
}
return "Age set to: $age";
}
?>
Explanation:
1. Function
Definition: The setAge function checks if the provided age is negative.
2. Throwing
the Exception: If the age is negative, the function throws an InvalidAgeException
with a specific error message.
Step 3:
Handle the Custom Exception
You can now use a try-catch block
to handle the InvalidAgeException when calling the setAge function.
<?php
try {
echo setAge(25); // Valid age
echo setAge(-5); // This will trigger the
exception
} catch
(InvalidAgeException $e) {
// Catch the custom exception and display
the error message
echo "Caught exception: " . $e->getMessage();
}
?>
Explanation:
1. Try Block: The
code attempts to set the age to 25 (which is valid) and then to -5 (which will
trigger the exception).
2. Catch
Block: If the InvalidAgeException is thrown, the catch block captures it, and
you can access the exception message using $e->getMessage(). This displays a
user-friendly message indicating that an invalid age was provided.
Complete
Code Example
Here’s the complete code all
together:
<?php
class InvalidAgeException
extends Exception {
public function __construct($message = "Invalid
age provided") {
parent::__construct($message);
}
}
function setAge($age)
{
if ($age < 0) {
throw new InvalidAgeException("Age
cannot be negative: $age");
}
return "Age set to: $age";
}
try {
echo setAge(25); // Valid age
echo setAge(-5); // This will trigger the
exception
} catch
(InvalidAgeException $e) {
echo "Caught exception: " . $e->getMessage();
}
?>
Output:
When running the complete code,
you will see:
vbnet
Copy code
Age set to:
25Caught exception: Age cannot be negative: -5
Summary
- You
created a custom exception class to handle invalid age inputs.
- You
demonstrated how to throw this custom exception and how to handle it using
try-catch blocks.
- This
approach provides a clear way to manage errors related to age input and
allows for informative error messaging.
2. Implement a function setAge($age) that throws the InvalidAgeException if the age is invalid. Test this function using try and catch to handle the exception and display the error message.
Step 1: Define the Custom Exception Class
First, ensure that you have the InvalidAgeException
class defined, which is used to represent invalid age-related errors.
<?php
class InvalidAgeException
extends Exception {
public function __construct($message = "Invalid
age provided") {
parent::__construct($message);
}
}
?>
Explanation:
- Class
Definition: InvalidAgeException extends the built-in Exception
class.
- Custom
Message: The constructor allows for a custom message,
which defaults to "Invalid age provided".
Step 2:
Implement the setAge($age) Function
Now, implement the setAge
function that checks if the provided age is valid.
<?php
function setAge($age)
{
// Check if the age is negative
if ($age < 0) {
// Throw InvalidAgeException for
invalid age
throw new InvalidAgeException("Age
cannot be negative: $age");
}
return "Age set to: $age";
}
?>
Explanation:
1. Function
Definition: setAge($age) accepts an age parameter.
2. Validation: The
function checks if $age is less than 0.
3. Throwing
the Exception: If the age is invalid, it throws an InvalidAgeException,
passing a specific message indicating the invalid input.
Step 3:
Handle the Exception with Try-Catch
You will now test the setAge
function using a try-catch block to handle any exceptions that may be thrown.
<?php
try {
// Test with a valid age
echo setAge(30); // This should succeed
echo "\n"; // New line for
clarity
// Test with an invalid age
echo setAge(-5); // This will trigger the
exception
} catch
(InvalidAgeException $e) {
// Handle the exception and display the
error message
echo "Caught exception: " . $e->getMessage();
}
?>
Explanation:
1. Try Block:
o
First, it attempts to set the age to 30, which is
valid. The function will return a success message.
o
Then, it attempts to set the age to -5, which is
invalid and will throw an exception.
2. Catch
Block:
o
If an InvalidAgeException is thrown, the catch
block will execute. It captures the exception and retrieves the message using $e->getMessage(),
displaying it to the user.
Complete
Code Example
Here's the complete code all
together for clarity:
php
<?php
class InvalidAgeException
extends Exception {
public function __construct($message = "Invalid
age provided") {
parent::__construct($message);
}
}
function setAge($age)
{
if ($age < 0) {
throw new InvalidAgeException("Age
cannot be negative: $age");
}
return "Age set to: $age";
}
try {
echo setAge(30); // Valid age
echo "\n"; // New line for
clarity
echo setAge(-5); // This will trigger the
exception
} catch
(InvalidAgeException $e) {
echo "Caught exception: " . $e->getMessage();
}
?>
Output
When running the complete code,
the output will be:
Age set to: 30
Caught
exception: Age cannot be negative: -5
Summary
- You
implemented the setAge function, which throws a custom exception for
invalid ages.
- You
tested the function using a try-catch block to handle exceptions and
display informative error messages.
- This
approach demonstrates structured error handling in PHP, allowing for
robust and user-friendly applications.