Section 9 : Exception Handling Flashcards
(13 cards)
What is the difference between C and C++ memory allocation?
Uses malloc() and free(), no constructor/destructor support.
int* p = (int*) malloc(sizeof(int));
free(p);
Uses new and delete, which also call constructors/destructors.
int* p = new int;
delete p;
How does error handling differ between C and C++?
C: Manual error checks using return values.
C++: Uses structured exception handling (try, throw, catch).
What are the three keywords used in C++ exception handling?
try: Marks a block of code to watch.
throw: Raises an exception.
catch: Handles the thrown exception.
What happens when an exception is thrown in a try block?
Execution jumps to the first matching catch block. Remaining code in try is skipped.
How are multiple catch blocks evaluated?
Top to bottom. The first matching block is executed. The default handler catch(…) should always come last.
Where should you handle exceptions?
Inside the function where the error happens. Don’t delegate low-level checks to main().
How do you re-throw an exception in nested try-catch?
Use throw; in an inner catch to pass the exception to an outer try block.
What does throw(int) after a function signature mean?
It means the function can only throw exceptions of type int. (Note: deprecated in modern C++.)
How do custom exception classes work in C++?
You inherit from std::exception and override what():
class DivisionByZero : public std::exception {
const char* what() const throw() { return “Division by zero”; }
};
Why use exception classes instead of error codes?
Cleaner design using polymorphism. Easier to manage with a single catch block.
What is the advantage of catch (const std::exception&)?
It can catch any exception derived from std::exception, thanks to polymorphism.
What are some common standard exceptions in C++?
std::bad_alloc (allocation failure)
std::bad_cast (invalid cast)
std::runtime_error, std::out_of_range, etc.