Recap - Safe Division
Part of the Logic & Flow section of Coddy's C++ journey — lesson 53 of 56.
Challenge
EasyCreate 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
numeratorrepresenting the number to be divided - A double
denominatorrepresenting the number to divide by
Your program should:
- Create a function named
safeDividethat takes two double parameters (numerator and denominator) - Inside the function, check if the denominator is equal to zero
- If the denominator is zero,
throwthe string"Division by zero error" - If the denominator is not zero, calculate the division result and return it as a double
- In the main function, call
safeDivideinside atryblock with the input values - Use a
catchblock to handle the thrown string exception - 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 errorRemember 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
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items8Basic Error Handling
Introduction to ExceptionsThe 'try' and 'catch' BlocksThe 'throw' KeywordDifferent Exception TypesThe Catch-All HandlerRecap - Safe Division