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

C++ throw Statement

throw is how you raise an alarm yourself when something is wrong, like shouting for help. Some code elsewhere can catch the alarm and deal with it.
Syntax
cpp
throw value;

try {
  throw value;
} catch (value_type variable_name) {
  // handle it
}

The throw Keyword

The throw keyword explicitly raises an exception: the instant a throw statement executes, C++ abandons the normal flow of execution and starts searching up the call stack for the nearest catch block whose type matches what was thrown.

Example: The throw Keyword

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 5;
	// 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 Different Data Types

You're free to throw primitive values, pointers, strings, or entirely custom types, but throwing a proper exception object — rather than a bare primitive — is the practice most real C++ code follows, since it can carry far more descriptive information about the failure.

Example: Throwing Different Data Types

cpp
// Include std::cout and std::cin
#include <iostream>
// Include std::string
#include <string>

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		// Throw an exception to signal an error
		throw std::string("Something went wrong");
	// 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;
}

Throwing Objects

Throwing objects is especially useful because the object itself can carry structured details about what went wrong — an error code, a message, related state — giving the code that eventually catches it much more to work with than a bare error number.

Example: Throwing Objects

cpp
// Include std::cout and std::cin
#include <iostream>
// Include std::string
#include <string>

// Define the type MyError
class MyError {
// Members below can be accessed from outside the class
public:
	std::string message;
	MyError(std::string msg) : message(msg) {}
};

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		// Throw an exception to signal an error
		throw MyError("Custom error object");
	// Handle the exception if one was thrown
	} catch (MyError &e) {
		std::cout << e.message << std::endl;
	}
	return 0;
}

Rethrowing an Exception

Sometimes a catch block can only partially handle an error and needs to let a higher-level handler deal with the rest; you can rethrow the exception currently being handled simply by writing throw with no operand, which preserves the original exception object.

Example: Rethrowing an Exception

cpp
// Include std::cout and std::cin
#include <iostream>

void inner() {
	// 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 << "Inner partially handles it" << std::endl;
		// Throw an exception to signal an error
		throw;
	}
}

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		inner();
	} catch (int e) {
		std::cout << "Outer fully handles: " << e << std::endl;
	}
	return 0;
}

noexcept Keyword

Declaring a function with the noexcept specifier promises callers it will never throw an exception.

If a noexcept function breaks that promise and throws anyway, the runtime immediately calls std::terminate, which ends the program rather than trying to unwind the stack.

Example: noexcept Keyword

cpp
// Include std::cout and std::cin
#include <iostream>

void safeFunction() noexcept {
	// Print to the console with cout
	std::cout << "Promises never to throw" << std::endl;
}

// Program execution starts in main()
int main() {
	safeFunction();
	// Return 0 to signal that the program finished successfully
	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. Throwing a pointer such as throw new Error(), which then must be caught as a pointer and deleted.
  2. Throwing an exception with no matching handler, which ends the program with std::terminate.
  3. Using throw e; instead of throw; to rethrow, which copies and can slice the exception.
🔒

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.