2

No doubt exceptions are usefull as they show programmer where he's using functions incorrectly or something bad happens with an environment but is there a real need to catch them?

Not caught exceptions are terminating the program but you can still see where the problem is. In well designed libraries every "unexpected" situation has actually workaround. For example using map::find instead of map::at, checking whether your int variable is smaller than vector::size prior to using index operator.

Why would anyone need to do it (excluding people using libraries that enforce it)? Basically if you are writing a handler to given exception you could as well write a code that prevents it from happening.

pkubik
  • 780
  • 6
  • 19
  • 3
    What happens if you're writing network code and the socket dies for some reason (basically gets disconnected). Most likely this is going to throw an exception, and if you're running say a server with multiple connections the proper thing to do would be to take said connection out of the list of active connections. – CrazyCasta Jan 16 '14 at 00:16
  • They should certainly never go uncaught. The underlying point here seems to be that you should write your code in a way as to prevent the exception from happening as best you can (and I'd agree with that), but that doesn't mean it's okay for your program to throw uncaught exceptions and crash. – nhgrif Jan 16 '14 at 00:18
  • *"Not caught exceptions are terminating the program but you can still see where the problem is"* -- No, not necessarily. Not all environments will report uncaught exceptions usefully. You should, at the very least, try to catch them in `main` so you can ensure useful reports. – Benjamin Lindley Jan 16 '14 at 00:21
  • @Benjamin Lindley - but even catching everything in main may not help that much when multithreaded apps are concerned. There was this famous problem on windows, for example, whereupon exceptions will disappear on system call boundaries and even debugger would be unable to catch those, basically forcing developers to catch everything as close to the potential throw sites as possible. – oakad Jan 16 '14 at 00:28

4 Answers4

6

Not all exceptions are fatal. They may be unusual and, therefore, "exceptions," but a point higher in the call stack can be implemented to either retry or move on. In this way, exceptions are used to unwind the stack and a nested series of function or method calls to a point in the program which can actually handle the cause of the exception -- even if only to clean up some resources, log an error, and continue on as before.

Ned
  • 937
  • 6
  • 10
  • I think I see your point. I was looking from a perspective of rather small project where every error can be easily fixed. However in big projects program might still need to work even if an error makes one module unusable. That actually makes sense. – pkubik Jan 16 '14 at 01:18
  • It is more than that. Consider a web server. It is a long-running process. You don't want it to shutdown every time a network connection drops. Instead, it needs to recover from any I/O error/exception it catches, clean up, and continue handling other requests as they come in. A dropped connection can generate an exception, but it isn't fatal. – Ned Jan 16 '14 at 01:31
  • But that's because of it's design. It expect from you to catch exceptions as it's a mechanism of reporting connection loss. I don't have experience nor knowledge to say whether it could be designed differently but it's still the thing I mentioned earlier - library design enforces to use exceptions. – pkubik Jan 16 '14 at 07:48
1

You can't always write code that prevents an exception. Just for an obvious example, consider concurrent code. Let's assume I attempt to verify that i is between (say) 0 and 20, then use i to index into some array. So, I check and i == 12, so I proceed to use it to index into the array. Unfortunately, in between the test and the indexing operation, some other thread added 20 to i, so by the time it's used as an index, it's not in range any more.

The concurrency has led to a race condition, so the attempt at assuring against an exceptional condition has failed. While it's possible to prevent this by (for example) wrapping each such test/use sequence in a critical section (or similar), it's often impractical to do so--first, getting the code correct will often be quite difficult, and second even if you do get it correct, the consequences on execution speed may be unacceptable.

Exceptions also decouple code that detects an exceptional condition from code that reacts to that exceptional condition. This is why exception handling is so popular with library writers. The code in the library doesn't have a clue of the correct way to react to a particular exceptional condition. Just for a really trivial example, let's assume it can't read from a file. Should it print a message to stderr, pop up a MessageBox, or write to a log?

In reality, it should do none of these. At least two (and possibly all three) will be wrong for any given program. So, what it should do is throw an exception, and let code at a higher level determine the appropriate way to respond. For one program it may make sense to log the error and continue with other work, but for another the file may be sufficiently critical that its only reasonable reaction is to abort execution entirely.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

Exceptions are very expensive, performance vise - thus, whenever performance matter you will want to write an exception free code (using "plain C" techniques for error propagation).

However, if performance is not of immediate concern, then exceptions would allow you to develop a less cluttered code, as error handling can be postponed (but then you will have to deal with non-local transfer of control, which may be confusing in itself).

oakad
  • 6,945
  • 1
  • 22
  • 31
  • Returning value from a function takes 2 instructions (assign return value register; jump to return address). Processing an exception takes few hundred lines of code (walking the stack back and checking for handlers, etc.). Thus, http://www.stroustrup.com/bs_faq2.html#exceptions-what-not – oakad Feb 19 '14 at 02:02
  • Start reading from here: https://github.com/mirrors/gcc/blob/master/libstdc%2B%2B-v3/libsupc%2B%2B/eh_catch.cc – oakad Mar 11 '14 at 01:00
0

I have used extensivelly exceptions as a method to transfer control on specific positions depending on event handling. Exceptions may also be a method to transfer control to a "labeled" position alog the tree of calling functions. When an exception happens the code may be thought as backtracking one level at a time and checking if that level has an exception active and executing it.

The real problem with exceptions is that you don't really know where these will happen. The code that arrives to an exception, usually doesn't know why there is a problem, so a fast returning back to a known state is a good action. Let's make an example: You are in Venice and you look at the map walking throught small roads, at a moment you arrive somewhere that you aren't able to find in the map. Essentially you are confused and you don't understand where you are. If you have the ariadne "μιτος" you may go back to a known point and restart to try to arrive where you want.

I think you should treat error handling only as a control structure allowing to go back at any level signaled (by the error handling routine and the error code).

George Kourtis
  • 2,381
  • 3
  • 18
  • 28
  • Exceptions don't take you back to a known *state* -- only a (semi-)known position in the call stack. Anything you've successfully changed prior to the failure is changed, exception or no. And (if you're not using RAII religiously, and in a few cases even when you are) you'll need to undo those changes yourself somehow. – cHao Jan 16 '14 at 01:05
  • Exceptions get you back to a known position, as you said some actions may be half done. That may be corrected by destructors and provision for allowing to destruct "half" objects. The worst case is when exceptions happen inside that code, then it is sure that something went very badly. But anyway, that's life. Exceptions that happen during exception handling, are handled from a higher level of exception code. – George Kourtis Jan 17 '14 at 20:31