Assignments On Class 23
Exception Handling in PHP
Here are some assignments related to exception handling in PHP, complete with solutions and explanations.
Assignment 1: Basic Exception Handling
Task: Create a function called calculateSquareRoot($number) that calculates the square root of a number. If the number is negative, it should throw an exception. Use a try and catch block to handle the exception and display a user-friendly message.
Assignment 2: Custom Exception Class
Task: Create a custom exception class named NegativeNumberException that extends the Exception class. Modify the calculateSquareRoot function to use this custom exception. Implement error handling with a try and catch block.
Assignment 3: Multiple Exceptions
Task: Write a function called divide($num1, $num2) that divides two numbers. If the denominator is zero, it should throw a DivisionByZeroException. If either of the parameters is not a number, it should throw a InvalidArgumentException. Handle both exceptions in a single try and catch block.
Assignment 4: Cleanup with Finally
Task: Modify the divide function to include a finally block that always outputs a message indicating that the division attempt has finished, regardless of whether an exception was thrown.
Solutions
Assignment 1: Basic Exception Handling
Task: Create a function called calculateSquareRoot($number) that calculates the square root of a number. If the number is negative, it should throw an exception. Use a try and catch block to handle the exception and display a user-friendly message.
Solution:
<?php
function calculateSquareRoot($number) {
if ($number < 0) {
throw new Exception("Cannot calculate the square root of a negative number.");
}
return sqrt($number);
}
try {
echo calculateSquareRoot(-9);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
Explanation:
- The calculateSquareRoot function checks if the input number is negative. If it is, an exception is thrown.
- In the try block, the function is called. If an exception is thrown, it is caught in the catch block, where an error message is displayed.
Assignment 2: Custom Exception Class
Task: Create a custom exception class named NegativeNumberException that extends the Exception class. Modify the calculateSquareRoot function to use this custom exception. Implement error handling with a try and catch block.
Solution:
<?php
class NegativeNumberException extends Exception {
public function errorMessage() {
return 'Error: ' . $this->getMessage();
}
}
function calculateSquareRoot($number) {
if ($number < 0) {
throw new NegativeNumberException("Cannot calculate the square root of a negative number.");
}
return sqrt($number);
}
try {
echo calculateSquareRoot(-16);
} catch (NegativeNumberException $e) {
echo $e->errorMessage();
}
?>
Explanation:
- The NegativeNumberException class extends the built-in Exception class and adds a method errorMessage() for formatting the error message.
- The calculateSquareRoot function throws a NegativeNumberException if the input is negative.
- In the try block, the function is executed, and if an exception is caught, the custom error message is displayed.
Assignment 3: Multiple Exceptions
Task: Write a function called divide($num1, $num2) that divides two numbers. If the denominator is zero, it should throw a DivisionByZeroException. If either of the parameters is not a number, it should throw a InvalidArgumentException. Handle both exceptions in a single try and catch block.
Solution:
<?php
class DivisionByZeroException extends Exception {}
class InvalidArgumentException extends Exception {}
function divide($num1, $num2) {
if (!is_numeric($num1) || !is_numeric($num2)) {
throw new InvalidArgumentException("Both parameters must be numbers.");
}
if ($num2 == 0) {
throw new DivisionByZeroException("Division by zero is not allowed.");
}
return $num1 / $num2;
}
try {
echo divide(10, 0);
// Uncomment the next line to test InvalidArgumentException
// echo divide('ten', 5);
} catch (DivisionByZeroException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} catch (InvalidArgumentException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
Explanation:
- Two custom exception classes, DivisionByZeroException and InvalidArgumentException, are created.
- The divide function checks if both parameters are numbers and if the denominator is zero, throwing the appropriate exception.
- In the try block, if an exception occurs, it is caught in the corresponding catch block, where an error message is displayed.
Assignment 4: Cleanup with Finally
Task: Modify the divide function to include a finally block that always outputs a message indicating that the division attempt has finished, regardless of whether an exception was thrown.
Solution:
<?php
class DivisionByZeroException extends Exception {}
class InvalidArgumentException extends Exception {}
function divide($num1, $num2) {
if (!is_numeric($num1) || !is_numeric($num2)) {
throw new InvalidArgumentException("Both parameters must be numbers.");
}
if ($num2 == 0) {
throw new DivisionByZeroException("Division by zero is not allowed.");
}
return $num1 / $num2;
}
try {
echo divide(10, 0);
} catch (DivisionByZeroException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} catch (InvalidArgumentException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "Division attempt completed.\n";
}
?>
Explanation:
- The finally block is added after the catch blocks. It will execute whether an exception was thrown or not, providing a message that indicates the end of the division attempt.
Conclusion
These assignments help students practice exception handling concepts in PHP, including basic error handling, custom exception classes, handling multiple exceptions, and using the finally block. Students should run these examples, modify them, and experiment with different scenarios to deepen their understanding of exception handling in PHP.