Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create 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 userInput that may or may not represent a valid integer

Your program should:

  1. Place the string-to-integer conversion inside a try block using std::stoi
  2. If the conversion succeeds, print the converted number with a success message
  3. Use a catch block to handle std::invalid_argument exceptions that occur when the string contains non-numeric characters
  4. 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 input

Remember 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;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow