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

C++ throw Statement

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 <iostream>

int main() {
	try {
		throw 5;
	} catch (int e) {
		std::cout << "Caught: " << e << std::endl;
	}
	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 <iostream>
#include <string>

int main() {
	try {
		throw std::string("Something went wrong");
	} catch (std::string &e) {
		std::cout << e << std::endl;
	}
	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 <iostream>
#include <string>

class MyError {
public:
	std::string message;
	MyError(std::string msg) : message(msg) {}
};

int main() {
	try {
		throw MyError("Custom error object");
	} 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 <iostream>

void inner() {
	try {
		throw 42;
	} catch (int e) {
		std::cout << "Inner partially handles it" << std::endl;
		throw;
	}
}

int main() {
	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 <iostream>

void safeFunction() noexcept {
	std::cout << "Promises never to throw" << std::endl;
}

int main() {
	safeFunction();
	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.