The 'try' and 'catch' Blocks
Part of the Logic & Flow section of Coddy's C++ journey — lesson 49 of 56.
The try and catch blocks work together to create a safety net for your code. You place potentially risky code inside a try block, and if an exception occurs, the program jumps to the corresponding catch block to handle the error gracefully.
Here's the basic syntax structure:
try {
// Code that might throw an exception
} catch (exception_type e) {
// Code to handle the exception
}A practical example involves converting strings to numbers using std::stoi, which can throw an std::invalid_argument exception if the string contains non-numeric characters:
try {
std::string input = "abc";
int number = std::stoi(input); // This will throw an exception
std::cout << "Number: " << number << std::endl;
} catch (std::invalid_argument& e) {
std::cout << "Invalid input! Please enter a valid number." << std::endl;
}When the exception occurs in the try block, the program immediately stops executing the remaining code in that block and jumps to the catch block. This prevents your program from crashing and allows you to provide meaningful feedback to users when things go wrong.
Challenge
EasyCreate a program that demonstrates safe string-to-number conversion using try and catch blocks. This challenge will test your understanding of how to handle exceptions that occur when converting user input from strings to integers.
The following input will be provided:
- A string
userInputthat may or may not represent a valid integer
Your program should:
- Place the string-to-integer conversion inside a
tryblock usingstd::stoi - If the conversion succeeds, print the converted number with a success message
- Use a
catchblock to handlestd::invalid_argumentexceptions that occur when the string contains non-numeric characters - In the catch block, print an error message indicating the input was invalid
Use the following exact output format:
For successful conversion:
Valid number: [converted_number]For invalid input that throws an exception:
Error: Invalid inputRemember that std::stoi will throw a std::invalid_argument exception when it encounters a string that cannot be converted to an integer. The try block should contain the conversion attempt, and the catch block should specify the exception type as std::invalid_argument& to handle this specific error. When an exception occurs, the program will immediately jump from the try block to the matching catch block, preventing the program from crashing.
Cheat sheet
Use try and catch blocks to handle exceptions safely:
try {
// Code that might throw an exception
} catch (exception_type e) {
// Code to handle the exception
}Example with std::stoi string-to-integer conversion:
try {
std::string input = "abc";
int number = std::stoi(input); // This will throw an exception
std::cout << "Number: " << number << std::endl;
} catch (std::invalid_argument& e) {
std::cout << "Invalid input! Please enter a valid number." << std::endl;
}When an exception occurs in the try block, the program immediately jumps to the corresponding catch block, preventing crashes and allowing graceful error handling.
Try it yourself
#include <iostream>
#include <string>
using namespace std;
int main() {
// Read input
string userInput;
cin >> userInput;
// TODO: Write your code below
// Use try-catch blocks with std::stoi to convert the string
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items8Basic Error Handling
Introduction to ExceptionsThe 'try' and 'catch' BlocksThe 'throw' KeywordDifferent Exception TypesThe Catch-All HandlerRecap - Safe Division