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

C++ try-catch

What is try-catch?

Unexpected problems like invalid user input can otherwise crash a program outright; C++'s try-catch blocks let you handle those situations gracefully instead. You place the risky code inside the try block and write the recovery logic inside the matching catch block.

Example: What is try-catch?

cpp
#include <iostream>

int main() {
	try {
		throw 1;
	} catch (int e) {
		std::cout << "Handled gracefully" << std::endl;
	}
	return 0;
}

Throwing and Catching Integers

C++ actually lets you throw almost any value, and throwing a plain integer is one of the simplest ways to signal an error code. The catch block that receives it behaves much like a function parameter, capturing whatever value was thrown.

Example: Throwing and Catching Integers

cpp
#include <iostream>

int main() {
	try {
		throw 404;
	} catch (int errorCode) {
		std::cout << "Error code: " << errorCode << std::endl;
	}
	return 0;
}

Catching Standard Exceptions

The standard header <stdexcept> is filled with ready-to-use exception classes that all inherit from std::exception and expose a handy what() method returning a human-readable description of what went wrong.

Example: Catching Standard Exceptions

cpp
#include <iostream>
#include <stdexcept>

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

Multiple Catch Blocks

A single try block can be followed by several catch blocks, and C++ matches the thrown exception against each one's declared type in order, executing only the first one that matches and skipping the rest entirely.

Example: Multiple Catch Blocks

cpp
#include <iostream>

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

The Catch-All Block

A catch-all block, written using three dots (...) instead of a specific type, catches any exception type that wasn't already handled by an earlier, more specific catch block, acting as a last line of defense so an unexpected error type doesn't crash the program.

Example: The Catch-All Block

cpp
#include <iostream>

int main() {
	try {
		throw 'x';
	} catch (int e) {
		std::cout << "int" << std::endl;
	} catch (...) {
		std::cout << "Caught by fallback" << 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.