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 -5Create a boolean variable named
checkPositive and set it to trueUse 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