0
0
C++programming~20 mins

Multiple catch blocks in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Multiple Exceptions with Multiple Catch Blocks in C++
πŸ“– Scenario: Imagine you are writing a simple program that divides two numbers. Sometimes, the user might enter zero as the divisor, which causes an error. Other times, the user might enter a non-number, causing a different error. You want to catch these errors separately and show clear messages.
🎯 Goal: You will create a program that uses try and catch blocks to handle different types of errors separately. This will help the program respond correctly to different problems.
πŸ“‹ What You'll Learn
Create two integer variables numerator and denominator with values 10 and 0 respectively.
Create a try block where you check if denominator is zero and throw an int exception with value 0 if true.
Add a catch block to catch the int exception and print "Error: Division by zero!".
Add another catch block to catch any other exceptions of type const char* and print "Error: Invalid input!".
πŸ’‘ Why This Matters
🌍 Real World
Handling errors properly is important in real-world programs to avoid crashes and to give users clear feedback when something goes wrong.
πŸ’Ό Career
Knowing how to use multiple catch blocks is a key skill for software developers to write safe and reliable C++ applications.
Progress0 / 4 steps
1
Create the initial variables
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 the try block with exception throwing
Add a try block. Inside it, check if denominator is zero. If yes, throw an int exception with value 0. Otherwise, calculate numerator / denominator and store it in an integer variable called result.
C++
Need a hint?

Use try { ... } and inside it use if (denominator == 0) throw 0;.

3
Add multiple catch blocks
Add two catch blocks after the try block. The first catch block should catch an int exception and print "Error: Division by zero!". The second catch block should catch a const char* exception and print "Error: Invalid input!".
C++
Need a hint?

Use catch (int) { ... } and catch (const char*) { ... } blocks with std::cout to print messages.

4
Print the final output
Add a main function around your code and include #include <iostream>. Run the program to see the output. The program should print Error: Division by zero!.
C++
Need a hint?

Make sure to include #include <iostream> and wrap your code inside int main() { ... }. Use std::cout to print the messages.