Are exceptions really for exceptional errors? [closed]

This sounds over-simplistic, but I think it makes sense to simply use exceptions where they are appropriate. In languages like Java and Python, exceptions are very common, especially in certain situations. Exceptions are appropriate for the type of error you want to bubble up through a code path and force the developer to explicitly catch. In my own coding, I consider the right time to add an exception when the error either can’t be ignored, or it’s simply more elegant to throw an exception instead of returning an error value to a function call etc.

Some of the most appropriate places for exceptions that I can think of offhand:

  • NotImplementedException – very appropriate way of designating that a particular
    method or function isn’t available, rather than simply returning without doing
    anything.
  • OutOfMemory exceptions – it’s difficult to imagine a better way of handling this
    type of error, since it represents a process-wide or OS-wide memory allocation
    failure. This is essential to deal with, of course!
  • NullPointerException – Accessing a null variable is a programmer mistake, and IMO
    this is another good place to force an error to bubble to the surface
  • ArrayIndexException – In an unforgiving language like C, buffer overflows
    are disastrous. Nicer languages might return a null value of some type, or in
    some implementations, even wrap around the array. In my opinion, throwing an
    exception is a much more elegant response.

This is by no means a comprehensive list, but hopefully it illustrates the point. Use exceptions where they are elegant and logical. As always with programming, the right tool for the right job is good advice. There’s no point going exception-crazy for nothing, but it’s equally unwise to completely ignore a powerful and elegant tool at your disposal.

Leave a Comment