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

C++ Exception Handling Introduction

Exception handling is planning what your program does when something goes wrong, like having a spare tire. It keeps one problem from ruining everything.
Syntax
cpp
try {
  // code that might throw
  throw value;
} catch (type variable_name) {
  // handle the error
}

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 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 42;
	// Handle the exception if one was thrown
	} catch (int e) {
		// Print to the console with cout
		std::cout << "Caught: " << e << std::endl;
	}
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>
// Include std::string
#include <string>

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

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		checkAge(-1);
	// Handle the exception if one was thrown
	} catch (std::string &e) {
		// Print to the console with cout
		std::cout << e << std::endl;
	}
	// Return 0 to signal that the program finished successfully
	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 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 caught" << std::endl;
	// Handle the exception if one was thrown
	} catch (double e) {
		// Print to the console with cout
		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 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("Something failed");
	// 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;
}

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 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 something unexpected" << 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, which slices.
  2. Placing a general catch(...) before specific ones.
  3. Not catching anything, so the program terminates.
🔒

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.