Exception Handling in C++
Object-Oriented Design - Section 2.4
Includes: Exception Objects, Try-
Catch, Inheritance, and Specifications
Introduction to Exceptions
• An exception is an unexpected event during
program execution.
• Why use Exceptions?
- Cleaner error handling
- Prevents abrupt termination
- More flexible than return codes
Syntax of try-catch Block
try {
// Code that may generate an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
- The `try` block encloses risky code.
- The `catch` block handles the error if thrown.
- Must appear in pairs — a `try` must be followed by
at least one `catch`.
Syntax of Throwing Standard
Exceptions
#include <stdexcept>
throw std::exception_type("Message");
- Use standard exceptions from <stdexcept>:
- logic_error
- runtime_error
- out_of_range
- Must catch using catch(exception& e) or similar.
Catching Exceptions
Catch exceptions by matching types:
catch (int e) {
// handle int
}
catch (const char* msg) {
// handle string
}
catch (...) {
// handle any exception
}
- You can use:
- Specific handlers for known types
- catch(...) as a catch-all fallback
Exception Objects
• In C++, exceptions are objects.
• They are thrown using 'throw' and caught
using 'catch'.
• Example:
Exception
Objects
Exception
Objects
Inheritance of Exception Classes
• Define specific error types using inheritance.
• Example:
class ZeroDivide : public MathException {
public:
ZeroDivide(const string& err) : MathException(err) {}
};
class NegativeRoot : public MathException {
public:
NegativeRoot(const string& err) : MathException(err) {}
};
Exception Recovery Strategies
• Logging
• Cleanup
• Restart computation
• Re-throw or ignore (empty catch block, not
recommended)
Generic Exception Class
• Base class for all exceptions:
class RuntimeException {
private:
string errorMsg;
public:
RuntimeException(const string& err) :
errorMsg(err) {}
string getMessage() const { return errorMsg; }
};
Summary
• Use throw, try, catch
• Build exception hierarchies
• Handle and recover cleanly
• Exception specification is deprecated in
modern C++