Menu
Coddy logo textTech

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.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

You 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: 100 or 49.99)
  • Second line: An integer representing the discount percentage (example: 20 or 150)

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

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow