In this tutorial, we'll cover the important topic of throwing and catching exceptions in C++. The goal is to teach you how to signal and handle exceptions, which will make your code more robust and less prone to crashes.
By the end of this tutorial, you will be able to understand what exceptions are, how to throw and catch them, and why they're an important part of programming in C++.
Prerequisites: A basic understanding of C++ and its syntax.
Exceptions are runtime errors that disrupt the normal flow of program execution. They usually occur due to some illegal operation in the code.
To throw an exception, we use the throw
keyword. It's often used inside a try
block when a condition that might lead to an exception is checked.
Exceptions are caught using catch
blocks. A catch
block follows a try
block and specifies the type of exception it can handle.
Without exception handling, an error encountered in the program would lead to termination. With exceptions, we can handle errors and prevent sudden termination.
try {
throw "This is an exception";
}
catch (const char* e) {
std::cout << "Caught exception: " << e << std::endl;
}
In this code, we throw a string exception and catch it. The catch
block prints the exception string to the console. The output would be Caught exception: This is an exception
.
try {
throw 10;
}
catch (int e) {
std::cout << "Caught an integer exception: " << e << std::endl;
}
catch (...) {
std::cout << "Caught an unknown exception" << std::endl;
}
Here, we throw an integer exception. The first catch
block catches it. If the exception were of any other type, the second catch
block (with the ellipsis) would catch it. The output would be Caught an integer exception: 10
.
In this tutorial, we've learned what exceptions are, how to throw and catch them, and why they're used in C++. The next step in learning would be to explore more complex examples and scenarios, and perhaps to learn about custom exceptions.
Write a program where you throw an integer, a character, and a string exception from inside a try
block, and catch them in separate catch
blocks.
Write a function that takes an integer as an argument and throws an exception if the integer is negative.
Write a function that takes a pointer as an argument and throws a custom exception if the pointer is null.
For each exercise, think about the best way to structure your try
and catch
blocks, and be sure to test your code thoroughly.
Happy Coding!