13

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

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
sivabudh
  • 31,807
  • 63
  • 162
  • 228

2 Answers2

7

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.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • 2
    Would it be appropriate to throw logic_error exception when we catch bugs in our code? e.g. use it instead of assert(). – sivabudh Feb 24 '10 at 22:38
  • 4
    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. – GManNickG Feb 24 '10 at 22:39
  • @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. – sivabudh Feb 24 '10 at 22:43
  • 2
    @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 Feb 24 '10 at 22:44
  • 1
    @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 Feb 24 '10 at 22:46
  • @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? – sivabudh Feb 24 '10 at 23:00
  • 1
    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 Feb 25 '10 at 08:11
2

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
  • 476,176
  • 80
  • 629
  • 1,111