← Back to C++ Course | Chapter 12: Exception Handling | Lesson 1 of 5

C++ Exception Handling Introduction

The try-catch Block

Exception handling gives you a structured way to deal with runtime errors without crashing the whole program: you wrap statements that might fail inside a try block, and any exception they throw gets caught and handled inside a matching catch block.

Example: The try-catch Block

cpp
#include <iostream>

int main() {
	try {
		throw 42;
	} catch (int e) {
		std::cout << "Caught: " << e << std::endl;
	}
	return 0;
}

Throwing Exceptions

The throw keyword is how you signal that a runtime error has occurred; the moment it executes, normal program flow stops immediately and control jumps straight to the nearest catch block whose type matches what was thrown.

Example: Throwing Exceptions

cpp
#include <iostream>
#include <string>

void checkAge(int age) {
	if (age < 0) throw std::string("Invalid age");
}

int main() {
	try {
		checkAge(-1);
	} catch (std::string &e) {
		std::cout << e << std::endl;
	}
	return 0;
}

Catching Multiple Exception Types

You can write several catch blocks in a row after a single try block, each one matching a different exception type. The compiler runs only the first catch block whose declared type matches the actual thrown exception, skipping the rest.

Example: Catching Multiple Exception Types

cpp
#include <iostream>

int main() {
	try {
		throw 3.14;
	} catch (int e) {
		std::cout << "int caught" << std::endl;
	} catch (double e) {
		std::cout << "double caught: " << e << std::endl;
	}
	return 0;
}

Standard Exceptions

The standard library provides ready-made exception classes in the stdexcept header, such as runtime_error and out_of_range, which you can throw yourself or catch generically through their common base class, std::exception.

Example: Standard Exceptions

cpp
#include <iostream>
#include <stdexcept>

int main() {
	try {
		throw std::runtime_error("Something failed");
	} catch (std::exception &e) {
		std::cout << e.what() << std::endl;
	}
	return 0;
}

Catch-All Block (...)

A catch-all block, written with three dots (...) as its parameter list instead of a specific type, catches literally any exception that wasn't matched by an earlier, more specific catch block — a useful safety net at the outermost level of a program.

Example: Catch-All Block (...)

cpp
#include <iostream>

int main() {
	try {
		throw 'x';
	} catch (int e) {
		std::cout << "int" << std::endl;
	} catch (...) {
		std::cout << "Caught something unexpected" << std::endl;
	}
	return 0;
}
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.