Section 9 : Exception Handling Flashcards

(13 cards)

1
Q

What is the difference between C and C++ memory allocation?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How does error handling differ between C and C++?

A

C: Manual error checks using return values.

C++: Uses structured exception handling (try, throw, catch).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the three keywords used in C++ exception handling?

A

try: Marks a block of code to watch.

throw: Raises an exception.

catch: Handles the thrown exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What happens when an exception is thrown in a try block?

A

Execution jumps to the first matching catch block. Remaining code in try is skipped.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How are multiple catch blocks evaluated?

A

Top to bottom. The first matching block is executed. The default handler catch(…) should always come last.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Where should you handle exceptions?

A

Inside the function where the error happens. Don’t delegate low-level checks to main().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you re-throw an exception in nested try-catch?

A

Use throw; in an inner catch to pass the exception to an outer try block.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does throw(int) after a function signature mean?

A

It means the function can only throw exceptions of type int. (Note: deprecated in modern C++.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do custom exception classes work in C++?

A

You inherit from std::exception and override what():

class DivisionByZero : public std::exception {
const char* what() const throw() { return “Division by zero”; }
};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Why use exception classes instead of error codes?

A

Cleaner design using polymorphism. Easier to manage with a single catch block.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the advantage of catch (const std::exception&)?

A

It can catch any exception derived from std::exception, thanks to polymorphism.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are some common standard exceptions in C++?

A

std::bad_alloc (allocation failure)

std::bad_cast (invalid cast)

std::runtime_error, std::out_of_range, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly