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

C++ try-catch

try-catch is like a safety net: you try something risky and, if it fails, catch the problem and respond calmly. The program does not crash.
Syntax
cpp
try {
  // risky code
} catch (exception_type variable_name) {
  // handle this type
} catch (...) {
  // handle any other exception
}

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 std::cout and std::cin
#include <iostream>

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		// Throw an exception to signal an error
		throw 1;
	// Handle the exception if one was thrown
	} catch (int e) {
		// Print to the console with cout
		std::cout << "Handled gracefully" << std::endl;
	}
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		// Throw an exception to signal an error
		throw 404;
	// Handle the exception if one was thrown
	} catch (int errorCode) {
		// Print to the console with cout
		std::cout << "Error code: " << errorCode << std::endl;
	}
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>
#include <stdexcept>

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		// Throw an exception to signal an error
		throw std::runtime_error("Failure");
	// Handle the exception if one was thrown
	} catch (std::exception &e) {
		// Print to the console with cout
		std::cout << e.what() << std::endl;
	}
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		// Throw an exception to signal an error
		throw 3.14;
	// Handle the exception if one was thrown
	} catch (int e) {
		// Print to the console with cout
		std::cout << "int" << std::endl;
	// Handle the exception if one was thrown
	} catch (double e) {
		// Print to the console with cout
		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 std::cout and std::cin
#include <iostream>

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		// Throw an exception to signal an error
		throw 'x';
	// Handle the exception if one was thrown
	} catch (int e) {
		// Print to the console with cout
		std::cout << "int" << std::endl;
	// Handle the exception if one was thrown
	} catch (...) {
		// Print to the console with cout
		std::cout << "Caught by fallback" << std::endl;
	}
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Catching an exception by value instead of by const&, which copies it and can slice derived exceptions.
  2. Placing a general catch (exception&) before more specific ones so they never run.
  3. Forgetting the braces around a try or catch body.
🔒

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.