In this tutorial, we will cover exception handling in C++ using try
and catch
blocks. Exception handling is a mechanism that separates code that detects and handles exceptional circumstances from the rest of your program. This is very important in producing robust and error-free code.
After completing this tutorial, you should be able to understand how to anticipate and handle potential errors in your code with the try
and catch
blocks in C++.
Prerequisites:
- Basic knowledge of C++ programming
- Understanding of C++ control structures
In C++, exception handling is accomplished with the try
, catch
, and throw
keywords.
Try
: Encloses the code that may potentially result in an error.Throw
: Throws an exception when an error occurs.Catch
: Captures and handles the exception thrown.Here are the steps to use try
and catch
blocks:
try
block.throw
statement to throw an exception if a problem is detected.catch
block.Best Practice:
- Always keep the try
block as short as possible and only include statements that might throw exceptions.
- Have separate catch
blocks for different types of exceptions to handle them differently.
try {
// Code that could throw an exception
throw "This is an exception!";
} catch(const char* e) {
// Handle the exception
std::cout << "Caught an exception: " << e << std::endl;
}
In this example, we throw a string exception and catch it in the catch
block. The output will be Caught an exception: This is an exception!
.
try {
// Code that could throw an exception
throw 10;
} catch(int e) {
// Handle the exception
std::cout << "Caught an integer exception: " << e << std::endl;
} catch(const char* e) {
// Handle the exception
std::cout << "Caught a string exception: " << e << std::endl;
}
Here, we throw an integer exception and have two catch
blocks. The first catch
block catches integer exceptions and the second catch
block catches string exceptions. The output will be Caught an integer exception: 10
.
We have covered how to handle exceptions in C++ using try
and catch
blocks. We learned how to anticipate and handle potential errors in our code.
Next, you should practice using try
and catch
with different types of exceptions. The more you practice, the more you'll understand how to handle exceptions.
Exercise 1: Write a program that throws a string exception if a number is less than 10.
Solution:
int number = 5;
try {
if(number < 10) {
throw "Number is less than 10!";
}
} catch(const char* e) {
std::cout << "Caught an exception: " << e << std::endl;
}
Exercise 2: Write a program that throws an integer exception if the division of two numbers is not a whole number.
Solution:
int num1 = 10;
int num2 = 3;
try {
if(num1 % num2 != 0) {
throw num1 / num2;
}
} catch(int e) {
std::cout << "Caught an exception: " << e << std::endl;
}
Tips for further practice:
- Try using multiple catch
blocks with different types of exceptions.
- Throw exceptions from within functions and catch them in the calling function.