0
0
C++programming~30 mins

Try–catch block in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Errors with Try-Catch Block in C++
📖 Scenario: Imagine you are building a simple calculator program that divides two numbers. Sometimes, the user might enter zero as the divisor, which causes an error. We want to handle this error gracefully so the program does not crash.
🎯 Goal: You will create a program that uses a try-catch block to catch division by zero errors and display a friendly message instead of crashing.
📋 What You'll Learn
Create two integer variables named numerator and denominator with exact values 10 and 0 respectively.
Create a boolean variable named error_occurred and set it to false.
Use a try block to perform the division numerator / denominator and store the result in an integer variable named result.
Use a catch block to catch a std::exception and set error_occurred to true.
Print "Error: Division by zero is not allowed." if error_occurred is true, otherwise print the division result.
💡 Why This Matters
🌍 Real World
Try-catch blocks are used in real programs to handle unexpected errors like file not found, network problems, or invalid user input without crashing.
💼 Career
Understanding error handling is important for writing reliable software and is a common requirement in programming jobs.
Progress0 / 4 steps
1
Create variables for division
Create two integer variables called numerator and denominator with values 10 and 0 respectively.
C++
Need a hint?

Use int numerator = 10; and int denominator = 0; to create the variables.

2
Add error flag variable
Create a boolean variable called error_occurred and set it to false.
C++
Need a hint?

Use bool error_occurred = false; to create the flag variable.

3
Use try-catch block for division
Write a try block that divides numerator by denominator and stores the result in an integer variable called result. Then write a catch block that catches std::exception& and sets error_occurred to true.
C++
Need a hint?

Use try { ... } and catch (const std::exception& e) { ... }. Throw an exception if denominator is zero.

4
Print the result or error message
Write an if statement that checks if error_occurred is true. If yes, print "Error: Division by zero is not allowed.". Otherwise, print the division result stored in result. Note: Declare result before the try block so it is accessible.
C++
Need a hint?

Use if (error_occurred) { std::cout << ... } else print the result.