0
0
C++programming~5 mins

Throwing exceptions in C++

Choose your learning style9 modes available
Introduction

Throwing exceptions helps your program handle errors in a clear way. It lets you stop normal work and jump to special error-handling code.

When a function cannot complete its task because of bad input.
When a file your program needs is missing or cannot be opened.
When a calculation results in an unexpected problem, like division by zero.
When you want to separate normal code from error-handling code for clarity.
Syntax
C++
throw exception_object;
You use the keyword throw followed by an object that describes the error.
The thrown object can be any type, but usually it's an error message or a special error class.
Examples
This throws an integer value 5 as an exception.
C++
throw 5;
This throws a standard runtime error with a message.
C++
throw std::runtime_error("File not found");
This throws a C-style string as an exception.
C++
throw "Invalid input";
Sample Program

This program tries to divide numbers. If the divisor is zero, it throws an exception. The try block runs the code that might throw. The catch block catches the error and prints a message.

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

int divide(int a, int b) {
    if (b == 0) {
        throw std::runtime_error("Division by zero is not allowed");
    }
    return a / b;
}

int main() {
    try {
        std::cout << divide(10, 2) << "\n";
        std::cout << divide(10, 0) << "\n";
    } catch (const std::runtime_error& e) {
        std::cout << "Error: " << e.what() << "\n";
    }
    return 0;
}
OutputSuccess
Important Notes

Always catch exceptions by reference to avoid copying.

Throwing exceptions stops normal code flow and jumps to the nearest matching catch block.

Use exceptions for unexpected errors, not for regular control flow.

Summary

Use throw to signal an error in your program.

Exceptions help separate error handling from normal code.

Catch exceptions to respond to errors gracefully.