CSC166 ยท 2078 ยท 5 marks
What is exception? Why exception handling is better to use? Explain exception handling with try.... catch by using suitable example.
What is exception? Why exception handling is better to use? Explain exception handling with try.... catch by using suitable example. [5]
Quick answer
An exception is an unusual or abnormal event (error condition) that occurs during the execution of a program and disrupts the normal flow of the program's instructions. Examples include division by zero, file not found, invalid memory access, and array index out of bounds.
Exception Handling in C++ with try...catch
What is an Exception?
Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.
Why is Exception Handling Better to Use?
| Without Exception Handling | With Exception Handling |
|---|---|
| Errors cause abrupt program termination | Program can handle errors gracefully |
| Error-checking code mixed with normal code | Clean separation of error-handling code |
| Difficult to maintain and read | Easier to maintain and debug |
| No mechanism to propagate errors | Errors can be propagated up the call stack |
Key benefits:
- Keeps the normal logic and error-handling logic separate
- Prevents abnormal program termination
- Allows recovery from runtime errors
- Makes code more readable and maintainable
Three Keywords of Exception Handling
- try -- Defines a block of code to be tested for errors while it is being executed. A block that may raise an exception is placed inside a try block (called protected code).
- throw -- Used to throw (signal) an exception when a problem is detected.
- catch -- Catches the exception thrown by the try block and handles it. The catch keyword indicates the catching of an exception.
Syntax
try {
// protected code
// code that might throw an exception
throw exception_value;
}
catch (type variable) {
// exception handler
// code to handle the exception
}
A try/catch block is referred to as protected code.
Example: Division by Zero
#include <iostream>
using namespace std;
int divide(int a, int b) {
if (b == 0) {
throw "Division by zero is not allowed!"; // throw exception
}
return a / b;
}
int main() {
int x = 10, y = 0;
try {
// protected code
int result = divide(x, y);
cout << "Result: " << result << endl;
}
catch (const char* msg) {
// exception handler
cout << "Exception caught: " << msg << endl;
}
cout << "Program continues after exception handling." << endl;
return 0;
}
Output:
Exception caught: Division by zero is not allowed!
Program continues after exception handling.
How it Works (Step by Step)
Step 1: divide(10, 0) is called inside the try block
Step 2: Inside divide(), b == 0, so throw is executed
Step 3: Control immediately transfers to the matching catch block
Step 4: catch(const char* msg) catches the thrown string
Step 5: Error message is displayed
Step 6: Program continues normally after the catch block
Summary
| Keyword | Role |
|---|---|
try | Encloses code that might cause an exception |
throw | Signals that an exception has occurred |
catch | Handles the exception and prevents program crash |
Exception handling ensures that even when errors occur at runtime, the program can handle them gracefully and continue execution rather than crashing abruptly.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.