0
0
C++programming~30 mins

Throwing exceptions in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Throwing exceptions
πŸ“– Scenario: Imagine you are writing a simple program that checks if a number is positive. If the number is negative, the program should stop and show an error message.
🎯 Goal: You will create a program that throws an exception when a negative number is found and handles it gracefully.
πŸ“‹ What You'll Learn
Create an integer variable named number with the value -5
Create a boolean variable named checkPositive and set it to true
Use a try block to check if number is negative and throw an exception with the message "Negative number found"
Use a catch block to catch the exception and print the exception message
πŸ’‘ Why This Matters
🌍 Real World
Throwing exceptions helps programs stop when something goes wrong, like invalid input or unexpected situations.
πŸ’Ό Career
Understanding exceptions is important for writing safe and reliable C++ programs in software development jobs.
Progress0 / 4 steps
1
Create the number variable
Create an integer variable called number and set it to -5.
C++
Need a hint?

Use int number = -5; to create the variable.

2
Create the checkPositive variable
Create a boolean variable called checkPositive and set it to true.
C++
Need a hint?

Use bool checkPositive = true; to create the variable.

3
Add a try block to throw an exception
Write a try block that checks if number is less than 0. If yes, throw a std::runtime_error exception with the message "Negative number found".
C++
Need a hint?

Use try { if (number < 0) throw std::runtime_error("Negative number found"); }.

4
Add a catch block to handle the exception and print the message
Add a catch block that catches std::runtime_error exceptions by reference as e and prints e.what() using std::cout.
C++
Need a hint?

Use catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; }.