C++ | Exception Handling | Question 12
What happens when a function throws an error but doesn’t specify it in the list of exceptions it can throw.
For example, what is the output of following program?
#include <iostream> using namespace std; // Ideally it should have been "int fun() (int)" int fun() { throw 10; } int main() { try { fun(); } catch ( int ) { cout << "Caught" ; } return 0; } |
(A) Compiler Error
(B) No compiler Error. Output is “Caught”
Answer: (B)
Explanation: C++ compiler doesn’t check enforce a function to list the exceptions that it can throw. In Java, it is enforced.
It is up to the programmer to specify. Being a civilized programmer, a programmer should specify the list.
Quiz of this Question