How to Throw Exception in C++: Syntax and Examples
In C++, you throw an exception using the
throw keyword followed by an object or value representing the error. This interrupts normal flow and transfers control to a matching catch block that handles the exception.Syntax
The basic syntax to throw an exception in C++ is:
throw expression;Here, expression can be any object or value that represents the error, such as an integer, string, or a custom exception class instance. The throw keyword signals that an error has occurred and transfers control to the nearest matching catch block.
cpp
throw expression;Example
This example shows how to throw and catch an exception using throw and catch. It throws a const char* string when a negative number is passed.
cpp
#include <iostream> int divide(int a, int b) { if (b == 0) { throw "Division by zero error"; } return a / b; } int main() { try { std::cout << divide(10, 2) << "\n"; // Works fine std::cout << divide(10, 0) << "\n"; // Throws exception } catch (const char* e) { std::cout << "Caught exception: " << e << "\n"; } return 0; }
Output
5
Caught exception: Division by zero error
Common Pitfalls
- Throwing exceptions of built-in types like
intorconst char*can make error handling less clear; prefer custom exception classes. - Not catching exceptions leads to program termination.
- Throwing exceptions inside destructors can cause unexpected behavior; avoid if possible.
- Always catch exceptions by reference to avoid slicing and unnecessary copying.
cpp
#include <iostream> // Wrong: throwing int void wrong() { throw 5; // Less informative } // Right: throwing a custom exception class #include <stdexcept> void right() { throw std::runtime_error("Error occurred"); } int main() { try { wrong(); } catch (int e) { std::cout << "Caught int exception: " << e << "\n"; } try { right(); } catch (const std::exception& e) { std::cout << "Caught exception: " << e.what() << "\n"; } return 0; }
Output
Caught int exception: 5
Caught exception: Error occurred
Quick Reference
Tips for throwing exceptions in C++:
- Use
throwfollowed by an error object. - Prefer standard or custom exception classes over primitive types.
- Catch exceptions by reference (
catch(const std::exception& e)). - Use
tryandcatchblocks to handle exceptions gracefully. - Avoid throwing exceptions from destructors.
Key Takeaways
Use the throw keyword followed by an error object to signal exceptions in C++.
Always catch exceptions by reference to handle errors properly and avoid slicing.
Prefer throwing standard or custom exception classes instead of primitive types.
Use try and catch blocks to manage exceptions and keep your program running safely.
Avoid throwing exceptions from destructors to prevent unexpected program termination.