throw
- C++ course
- Beginner
- Lesson 101/116
- 4 min
Learn to throw your own exceptions with throw.
Throwing exceptions with throw
To throw your own exception, you use the throw keyword. It is followed by a value or an exception object; this value propagates upward until an appropriate catch block handles it.
if (age < 0) {
throw std::runtime_error("negative age");
}Here, if age is negative, a std::runtime_error is thrown. The caller can catch it with try/catch. throw lets the program clearly report an abnormal condition.
throw and type choice
You can throw any value with throw; but using types derived from std::exception is the best practice. This way, a catch (const std::exception& e) block catches the exception regardless of the specific type.
throw std::runtime_error("disk full");
throw std::invalid_argument("invalid code");
throw std::out_of_range("out of bounds");All three types derive from std::exception. Each constructor takes a description string, accessed via .what(). Choosing the right type makes the error source easier to understand.
Practice Throw on a negative age
Add the #include <stdexcept> header. Define int age = -5;. Inside a try block, write if (age < 0) throw std::runtime_error("negative age");. In a catch (const std::exception& e) block, call cout << e.what() << endl;.
Starter code
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
int age = -5;
// throw if age<0, catch and print the message
return 0;
}Sample solution
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
int age = -5;
try {
if (age < 0) throw std::runtime_error("negative age");
} catch (const std::exception& e) {
cout << e.what() << endl;
}
return 0;
}Expected output
negative age
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: throw call
if (x < 0) {
____ std::runtime_error("negative");
}
if (x < 0) {
throw std::runtime_error("negative");
}
Explanation: throw throws an exception.
2 throw std::runtime_error("x") requires which header?
- <iostream>
- <stdexcept> Correct answer
- <string>
- <vector>
Explanation: runtime_error is defined in the stdexcept header.
3 Match each exception type with its scenario
| Term | Meaning |
|---|---|
runtime_error |
runtime error |
invalid_argument |
invalid input |
out_of_range |
out of bounds |