Throwing an Exception
Part of the Logic & Flow section of Coddy's PHP journey — lesson 55 of 68.
Sometimes you need to signal that something has gone wrong in your code and stop normal execution. The throw keyword allows you to manually create and throw an exception, giving you control over when and why your program should handle an error condition.
When you throw an exception, you create a new Exception object and provide it with a descriptive message about what went wrong. This exception will immediately stop the current code execution and look for a catch block to handle it.
<?php
function checkAge($age) {
if ($age < 0) {
throw new Exception("Age cannot be negative");
}
echo "Age is valid: " . $age;
}
try {
checkAge(-5);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>The throw statement requires the new Exception() syntax, where you pass a string message describing the problem. This message can later be retrieved using the getMessage() method in your catch block, making it easier to understand what went wrong and respond appropriately.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou will receive two inputs: a number representing a price and a number representing a discount percentage. Both inputs will be provided as numbers (the price might be a decimal, and the discount percentage will be an integer between 0 and 100).
Read both inputs and create a function called calculateFinalPrice that accepts two parameters: the price and the discount percentage. Inside this function, check if the discount percentage is greater than 100 or less than 0. If either condition is true, throw a new Exception with the message "Invalid discount percentage". If the discount is valid, calculate the final price after applying the discount and return it.
Use a try...catch block to call the function with the provided inputs. In the try block, call the function and print "Final price: " followed by the calculated final price. In the catch block, handle the exception by printing "Error: " followed by the exception message using the getMessage() method.
Input format:
- First line: A number representing the price (example:
100or49.99) - Second line: An integer representing the discount percentage (example:
20or150)
Expected output:
- If the discount is valid:
Final price:followed by the calculated price after discount - If the discount is invalid:
Error: Invalid discount percentage
Cheat sheet
Use the throw keyword to manually create and throw exceptions:
throw new Exception("Error message");When an exception is thrown, it stops normal execution and looks for a catch block to handle it:
<?php
function checkAge($age) {
if ($age < 0) {
throw new Exception("Age cannot be negative");
}
echo "Age is valid: " . $age;
}
try {
checkAge(-5);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>Use getMessage() method in the catch block to retrieve the exception message.
Try it yourself
<?php
// Read inputs
$price = floatval(fgets(STDIN));
$discountPercentage = intval(fgets(STDIN));
// TODO: Write your code below
// Create the calculateFinalPrice function
// Use try...catch block to call the function and handle exceptions
// Print the appropriate output
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise5Student Gradebook
Project Setup: Data StructureAdding a New StudentAdding a Grade to a StudentCalculating Student's AverageFinding the Top StudentGenerating a Report Card8Error and Exception Handling
Understanding PHP ErrorsThe 'try...catch' BlockThe 'finally' BlockThrowing an ExceptionCreating a Custom ExceptionUsing a Custom ExceptionRecap: Input Validation3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting