Throwing exceptions helps your program handle errors in a clear way. It lets you stop normal work and jump to special error-handling code.
When a function cannot complete its task because of bad input.
When a file your program needs is missing or cannot be opened.
When a calculation results in an unexpected problem, like division by zero.
When you want to separate normal code from error-handling code for clarity.
Syntax
C++
throw exception_object;
You use the keyword throw followed by an object that describes the error.
The thrown object can be any type, but usually it's an error message or a special error class.
Examples
This throws an integer value 5 as an exception.
C++
throw5;
This throws a standard runtime error with a message.
C++
throw std::runtime_error("File not found");
This throws a C-style string as an exception.
C++
throw"Invalid input";
Sample Program
This program tries to divide numbers. If the divisor is zero, it throws an exception. The try block runs the code that might throw. The catch block catches the error and prints a message.
C++
#include <iostream>
#include <stdexcept>
int divide(int a, int b) {
if (b == 0) {
throw std::runtime_error("Division by zero is not allowed");
}
return a / b;
}
int main() {
try {
std::cout << divide(10, 2) << "\n";
std::cout << divide(10, 0) << "\n";
} catch (const std::runtime_error& e) {
std::cout << "Error: " << e.what() << "\n";
}
return0;
}
OutputSuccess
Important Notes
Always catch exceptions by reference to avoid copying.
Throwing exceptions stops normal code flow and jumps to the nearest matching catch block.
Use exceptions for unexpected errors, not for regular control flow.
Summary
Use throw to signal an error in your program.
Exceptions help separate error handling from normal code.
Catch exceptions to respond to errors gracefully.
Practice
(1/5)
1. What does the throw keyword do in C++?
easy
A. It defines a new function.
B. It catches an exception.
C. It signals an error by raising an exception.
D. It declares a variable.
Solution
Step 1: Understand the purpose of throw
The throw keyword is used to signal that an error or exceptional condition has occurred in the program.
Step 2: Differentiate from other keywords
throw does not catch exceptions (that's catch), nor does it define functions or declare variables.
Final Answer:
It signals an error by raising an exception. -> Option C
Quick Check:
throw = signal error [OK]
Hint: Remember: throw means "raise an error" [OK]
Common Mistakes:
Confusing throw with catch
Thinking throw declares variables
Assuming throw defines functions
2. Which of the following is the correct syntax to throw an integer exception with value 10?
easy
A. throw int 10;
B. throw(int 10);
C. throw new int(10);
D. throw 10;
Solution
Step 1: Recall correct throw syntax
In C++, to throw an exception, you use throw followed by the value or object, without parentheses or type keywords.
Step 2: Analyze each option
throw 10; uses throw 10; which is correct. throw(int 10); incorrectly declares a type inside parentheses, invalid syntax. throw int 10; incorrectly adds type keyword. throw new int(10); throws a pointer, which is allowed but not the simplest form here.
Final Answer:
throw 10; -> Option D
Quick Check:
Simple throw syntax = throw value; [OK]
Hint: Use throw followed directly by value, no parentheses [OK]
The code throws an integer 5, which is caught by the first catch block for int. The second catch block is a catch-all for any other exceptions.
Step 2: Check for syntax or logic errors
Multiple catch blocks are allowed and correctly ordered from specific to general. The catch blocks have correct parameter types. Throwing an int matches the first catch.
Final Answer:
No error, code is correct -> Option A
Quick Check:
Proper catch blocks for thrown int = correct code [OK]
Hint: Multiple catch blocks allowed; order matters [OK]
Common Mistakes:
Thinking multiple catch blocks cause error
Missing parameter type in catch
Throwing incompatible data type
5. Consider this function that throws exceptions based on input:
<pre>void checkValue(int x) {
if (x < 0) throw std::string("Negative value");
else if (x == 0) throw 0;
else throw 3.14;
}
What is the best way to catch all exceptions thrown by checkValue and print a message for each type accordingly?
hard
A. Use a single catch block with catch(...) only.
B. Use separate catch blocks for std::string, int, and double types.
C. Use only catch(int) block.
D. Use try without any catch block.
Solution
Step 1: Identify exception types thrown
The function throws three different types: std::string, int, and double.
Step 2: Determine how to catch each type
To handle each exception properly, separate catch blocks for each type are needed. Using only catch(...) catches all but cannot distinguish types. Catching only int misses others. No catch block causes program termination on exception.
Final Answer:
Use separate catch blocks for std::string, int, and double types. -> Option B
Quick Check:
Multiple catch blocks for different types = best practice [OK]
Hint: Catch each thrown type separately for clear handling [OK]
Common Mistakes:
Using only catch(...) and missing type info
Catching only one exception type
Not using any catch block
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.