Which of the following best explains why exception handling is important in C++?
Think about how handling errors separately can improve code clarity and reliability.
Exception handling allows programmers to write normal code without cluttering it with error checks. When an error occurs, the program jumps to special code that handles the error, improving readability and robustness.
What is the output of this C++ code?
#include <iostream> using namespace std; int main() { try { throw 5; cout << "After throw" << endl; } catch (int e) { cout << "Caught exception: " << e << endl; } cout << "Program continues" << endl; return 0; }
Remember that code after throw inside try is not executed.
The throw 5; immediately transfers control to the catch block. The line after throw is skipped. Then the program continues after the try-catch block.
What happens when this code runs without any exception handling?
#include <iostream> using namespace std; int divide(int a, int b) { return a / b; } int main() { int x = 10, y = 0; cout << divide(x, y) << endl; return 0; }
Think about what happens when you divide by zero in C++ without protection.
Dividing by zero causes undefined behavior, often a runtime crash or error. Without exception handling, the program cannot recover gracefully.
Which statement correctly describes a benefit of using exception handling instead of error codes?
Consider how exception handling separates error logic from normal logic.
Exception handling lets you write clean code by handling errors in one place, not after every function call. This improves maintainability and readability.
What is the output of this C++ program?
#include <iostream> using namespace std; int main() { try { try { throw "Error inside inner try"; } catch (const char* msg) { cout << "Inner catch: " << msg << endl; throw; } } catch (const char* msg) { cout << "Outer catch: " << msg << endl; } cout << "Program ends" << endl; return 0; }
Notice the throw; inside the inner catch rethrows the exception.
The inner catch prints its message then rethrows the exception. The outer catch catches it again and prints its message. Finally, the program prints "Program ends".