Menu
Coddy logo textTech

Recap - Safe Division

Part of the Logic & Flow section of Coddy's C++ journey — lesson 53 of 56.

challenge icon

Challenge

Easy

Create a program that implements safe division using comprehensive exception handling. This challenge will test your ability to combine function design with exception management to handle division by zero errors gracefully.

The following inputs will be provided:

  • A double numerator representing the number to be divided
  • A double denominator representing the number to divide by

Your program should:

  1. Create a function named safeDivide that takes two double parameters (numerator and denominator)
  2. Inside the function, check if the denominator is equal to zero
  3. If the denominator is zero, throw the string "Division by zero error"
  4. If the denominator is not zero, calculate the division result and return it as a double
  5. In the main function, call safeDivide inside a try block with the input values
  6. Use a catch block to handle the thrown string exception
  7. Print the appropriate message based on whether the division succeeds or fails

Use the following exact output format:

For successful division:

Result: [division_result]

For division by zero error:

Error: Division by zero error

Remember that when the denominator is zero, your function should immediately throw an exception before attempting the division. The catch block should specify the type const char* to handle the thrown string literal. When an exception is thrown, the program will jump directly from the throw statement to the matching catch block, preventing any division by zero from occurring and allowing your program to handle the error gracefully instead of crashing.

Try it yourself

#include <iostream>
using namespace std;

int main() {
    // Read input
    double numerator, denominator;
    cin >> numerator >> denominator;
    
    // TODO: Write your code here
    // Create the safeDivide function above main()
    // Use try-catch block to handle exceptions
    
    return 0;
}

All lessons in Logic & Flow