Throwing Exceptions in C++
Lesson Introduction
Hello! Today, we will learn about throwing exceptions in C++, which is vital for writing robust programs. Think of exceptions like traffic signals. When driving, if you see a red light, you stop to avoid collisions—a clear sign something needs attention. Similarly, exceptions signal problems in our code, allowing us to handle errors smoothly. By the end, you'll know how to throw and catch exceptions, making your programs more resilient.
Throwing Exceptions
To "throw" an exception means to signal that something unusual has occurred. In C++, we use the throw keyword to do this. It’s like raising your hand to say, "Wait, there's a problem!"
Here’s a simple example. Imagine you ask a vending machine for a snack that's out of stock. The machine needs to inform you that it can't complete your request:
Output:
Catching Exceptions: Part 1
Imagine we have a function that can throw an error:
In this case, everything is fine, and the function is successfully executed. But if we call it like this, it will throw an error:
This way, our function is designed to warn the program with an error that something went wrong. However, we don't want the program to terminate every time this error appears. Let's learn how to handle it.
Catching Exceptions: Part 2
In C++, we can handle exceptions with a special try-catch block. The program tries to execute the code inside the try, and in case it fails with an exception, executes the code inside the catch.
Let’s modify our example:
When the give_order function is called with order = 5 and stock = 3, it will throw a std::runtime_error because the order exceeds the stock.
The catch block catches exceptions of type std::runtime_error. If the exception is caught, it prints the error message using e.what() where e is the exception object caught. This prevents the program from crashing and allows you to handle the error however you want.
This way, your program continues to run and provides a meaningful handling of an error.
