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?

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
}

chevron_right


(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

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up