views:

254

answers:

2

If you use std::logic_error exception in your code, in what case do you use it for?

+2  A: 

logic_error is the base for these exceptions: domain_error, invalid_argument, length_error, out_of_range.

Those are all logical errors: Somethings wrong with the input such that the output would be illogical. So I'd say you usually don't need to use it directly, since those four cover any logic errors I can think of. But those give you an idea of what the category is.

GMan
Would it be appropriate to throw logic_error exception when we catch bugs in our code? e.g. use it instead of assert().
ShaChris23
Probably not. `assert`'s are for *programmer errors*. Checking something is null, etc., things that *shouldn't happen*, regardless of user input. Contrarily, exceptions are for things that are expected to happen once in a while, and be caught and processed.
GMan
@GMan: Which exception could I use instead of our good ol' assert to catch bugs that could happen during run-time? I think assert is great, but I would like to use exception to handle them for graceful exits.
ShaChris23
@GMan, that's what i think too. See also Eric Lippert's opinion here: http://stackoverflow.com/questions/990115/do-i-have-to-break-after-throwing-exception and the discussion on SO here: http://stackoverflow.com/questions/2201493/using-default-in-a-switch-statement-when-switching-over-an-enum
Johannes Schaub - litb
@ShaChris23, `assert` can exit very gracefully, giving you a line number and the filename where the error occured, even showing the condition that failed to hold. Any exception will exit less gracefully, i think.
Johannes Schaub - litb
@litb - at the very top of my main()/thread loop I put a catch() statement which does logging or transmit error message over network. Is there a way I can customize assert to achieve similar effect?
ShaChris23
Well, as the name implies, it _is_ used for flaws in the program logic, things which could have been (at least in theory) prevented by better coding. (That's the main difference to `std::runtime_error`.) So, in a sense, it was meant to be used where `assert` is commonly used, too.
sbi
+2  A: 

As GMan already pointed out, it's primarily a base for other exception classes. You might consider using it directly for something that's basically an assertion. E.g. if some code depends on a particular object having been constructed before it executes, it might be appropriate for it to throw a logic_error (rather than a derivative) if it executes and that object hasn't been constructed yet.

Jerry Coffin