0
0
C++programming~5 mins

Try–catch block in C++

Choose your learning style9 modes available
Introduction

A try-catch block helps your program handle errors without crashing. It lets you try some code and catch problems if they happen.

When reading a file that might not exist.
When dividing numbers and the divisor could be zero.
When converting user input to a number that might be invalid.
When working with network connections that can fail.
Syntax
C++
try {
    // code that might cause an error
} catch (const ExceptionType& e) {
    // code to handle the error
}
The try block contains code that might cause an error.
The catch block handles the error if it happens.
Examples
This tries to convert an invalid string to an integer and catches the error to print a message.
C++
try {
    int x = std::stoi("abc");
} catch (const std::exception& e) {
    std::cout << "Error: " << e.what() << std::endl;
}
This throws a custom error and catches it to show the message.
C++
try {
    throw std::runtime_error("Oops!");
} catch (const std::runtime_error& e) {
    std::cout << "Caught: " << e.what() << std::endl;
}
Sample Program

This program tries to divide 5 by 0. It throws an error and catches it to print a friendly message instead of crashing.

C++
#include <iostream>
#include <stdexcept>

int main() {
    try {
        int a = 5;
        int b = 0;
        if (b == 0) {
            throw std::runtime_error("Cannot divide by zero");
        }
        int c = a / b;
        std::cout << "Result: " << c << std::endl;
    } catch (const std::runtime_error& e) {
        std::cout << "Error caught: " << e.what() << std::endl;
    }
    return 0;
}
OutputSuccess
Important Notes

Always catch exceptions by reference to avoid slicing.

You can have multiple catch blocks for different error types.

If no catch matches, the program will terminate.

Summary

Try-catch blocks help handle errors safely.

Put risky code inside try and handle errors in catch.

This keeps your program running smoothly even when problems happen.