Alex Rivera | Logout

How to make an intelligent decision about which standard exception to throw?

Asked 2011-10-02T04:41:39.953
27

We know that the exception class has two derived classes: logic_error and runtime_error.

logic_error has four derived classes: domain_error, invalid_argument, length_error and out_of_range.

runtime_error has three derived classes: range_error, overflow_error and underflow_error.

While some of them are self-explanatory, like overflow_error and underflow_error, some are not that clear, especially range_error, both MSDN and cplusplus just say "to report a range error", which is close to saying nothing, how it is different out_of_range and domain_error???

Another question is when I throw an exception, which one should I choose? For example, In reverse_string(char* s), which exception to throw when s is NULL? In float calc_ellipse_area(float a, float b), which to throw when a or b is <=0? Which to throw when a == b (strictly speaking, circle is not an ellipse!)?

Finally, practically speaking, does it really matter if I throw an exception which is not correctly categorized?

Edit
Report

1 Answer

20

A logic error is the (theoretically) result of a programmer error. A runtime error is something that could not easily have been prevented by the programmer.

When you write a function, it is useful to document its preconditions and/or assumptions. If those preconditions are broken, it is a logic error.

A runtime error is usually due to something external: a file operation failed, a printer is offline, a DLL could not be loaded.

If a path parameter is malformed, that is a logic error. If it is a valid path string, but does not exist, or you don't have permission to access it, that is a runtime error.

Sometimes it becomes arbitrary. Bad user input is probably a runtime error, but failure to validate user input is more of a logic error. It may not be obvious which is the case in a particular situation.

If something starts in 01 Feb 2011, a finish date of "01 Jan 2011" is an invalid argument, while "31 Feb 2011" is out of range. A finish date of "fish and chips" is a domain error. Length errors are often about buffer size, but that might also include too much or too little input data or something like that.

A range error is similar to an out of range error, except for the context (runtime, not logic). e.g. Number of printers available = 0. Overflow and underflow are more or less self-explanatory.

In the end, use them in a way that you and your colleagues find meaningful -- or possibly don't use them at all. Some people just use std::exception for everything.

It is only really important if you are going to handle different exceptions differently. If you are just going to display (or log) a message and carry on, it doesn't matter what exception(s) you use.

answered 2011-10-02T08:30:26.820

Your Answer