C++ has an mechanism for throwing exceptions. Many other languages have this fea
ID: 3843042 • Letter: C
Question
C++ has an mechanism for throwing exceptions. Many other languages have this feature as well. One interesting way that exception handing varies from one language to another is what type of "thing" can be thrown. Java, for example, has a class called Exception (specifically, java.lang.Exception). The only things you an "throw" in Java are objects of type Exception (or of types that are derived via inheritance from Exception). What is the case for C++-i.e., what kind of value can be "thrown" in C++?Explanation / Answer
In C++, both basic types and objects can be thrown as exception.
Ex:
int main()
{
int x = -1;
// Some code
cout << "Before try ";
try {
cout << "Inside try ";
if (x < 0)
{
throw x;
cout << "After throw (Never executed) ";
}
}
catch (int x ) {
cout << "Exception Caught ";
}
cout << "After catch (Will be executed) ";
return 0;
}
There is a special catch block called ‘catch all’ catch(…) that can be used to catch all types of exceptions. For example, in the following program, an int is thrown as an exception, but there is no catch block for int, so catch(…) block will be executed.
int main()
{
try {
throw 10;
}
catch (char *excp) {
cout << "Caught " << excp;
}
catch (...) {
cout << "Default Exception ";
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.