pseudonym_127
pseudonym_127

Reputation: 357

Having different exception classes

I have a simple question about exceptions. Why is it the case that people frequently use separate classes for each type of exception, is it because we may want to handle different exceptions in different manner? (as compared to just catching "..." for instance).

Upvotes: 0

Views: 68

Answers (2)

Arne Mertz
Arne Mertz

Reputation: 24576

In addition to having different data to provide in exceptional cases and the different manner of handling different errors, you can also decide to handle them in different places. Consider a function loadFileContentIntoMemory that can throw errors due to file system errors (access rights, file not found etc.) and due to memory problems (typically std::bad_alloc). You might want to handle one kind of error while the other can not be handled at the same point. For example, you might want to catch file related errors and just try another filename, while it's normally hard to do anything about bad_alloc at any point of a program, so many programs catch it at a very top level location to issue an error message and terminate the program.

Upvotes: 0

AnT stands with Russia
AnT stands with Russia

Reputation: 320391

Exception objects are not just for indicating that something happened, so catch (...) would be a very primitive way to use the power of exceptions.

Each exception object will typically carry a "payload": information from the place where the exception occurred to the place where it is handled. As an exception flies up the unwinding call stack, the functions along the way might intercept it, enrich it with extra information and send it on its way further up. Different functional modules in the program will send completely different information to the exception handler, which is why you will need different exception classes to carry that information.

For example, parser exception might carry information about line number and nature of syntax error. File system exception might carry information about file name and error code. Dynamic memory exception might carry information about specific memory operation and memory block size. And so on. To store and carry those completely unrelated sets of data you'd normally define different exception types.

Upvotes: 4

Related Questions