Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Why have many programmers moved to using exception handling for input or output? For these programmers, what is the motivation behind this decision?

share|improve this question

put on hold as primarily opinion-based by gnat, gbjbaanb, DougM, Snowman, Bart van Ingen Schenau 12 hours ago

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

12  
The abundance of C programmers and projects in C disagree with your claims of "almost all" –  whatsisname 21 hours ago
1  
Java programmers don't get a choice! –  James Anderson 18 hours ago
2  
"almost all programmers, in almost all cases" - are you begging for downvotes? –  Doc Brown 18 hours ago
1  
Survival of the fittest. Exceptions work better than the alternative. –  Mason Wheeler 15 hours ago
1  
Damon, welcome to Stack Exchange! Robert Harvey and I have edited your question to be more user friendly (it doesn't add any information to the question to tell us that you're a beginner) and to be less opinion based. Stack Exchange is about experts answering answerable questions, and a question that is simply asking for opinions won't receive a lot of support on SO. See help center and How to Ask. –  durron597 12 hours ago

7 Answers 7

Because input and output are unreliable.

Exceptions are, in part, an acknowledgement that there are going to be conditions which the software cannot reasonably recover from.

  1. Premature end-of-line termination, syntax error or any number of validation error conditions,
  2. Inputs are too long or large to reasonably accomodate,
  3. Keyboard gets unplugged,
  4. Hard disk runs out of space, etc.

Exceptions are the programmer's way of saying "I can't continue under the present conditions." In essence, when you throw an exception, you're giving up and asking for a do-over.

You can do this without gracefully exiting your input/output subroutine or even worrying about memory management, because the orderly disposal of the relevant objects is already built into the exception-handling mechanism.

You can control where in your code the exception gets handled without elaborate if structures, intricate state mechanisms or call tree tracking.

share|improve this answer

Why have almost all programmers, in almost all cases, moved to using exception handling for input or output?

Because exceptions (as opposed to error code return values) cannot be ignored.

The typical code for i/o calls before exceptions, was usually written in terms of printf/scanf/gets/puts.

These functions return values that allow the developer to check for errors, but that is not trivial.

Most developers, knowing the error handling is not trivial, simply ommit it; They tend to think a typical fscanf call should look like this:

int a;
FILE *f = /* ... */;
fscanf(f, "%d", &a);

when it should probably look like this:

switch(fscanf(f, "%d", &a))
{
case EOF:
    // todo: handle EOF case
    break;
case 0:
    puts("could not read 'a'");
    break;
case 1:
    // handle success case
    break;
}

This code can (to a point) be extracted into a function, parametrized and (probably) hidden inside a wrapper on scanf, or a macro (both of which have downsides).

If you do not write it though, your application simply doesn't handle the errors. On the other hand, exceptions give you more useful error information, propagate naturally up the call stack and cannot be ignored (if you do, they will stop your application).

share|improve this answer
    
Not to mention that interfaces of some methods are just incredibly obfuscated. Some function might return -1 to indicate an error, some might return 0. Some functions will set output parameters even when it fails, some don't. Exceptions are just one more step in making it easier to write increasingly safe code, without having to rely on the programmer understand all the intricacies of what they're trying to do. Languages like Java or C# exploit this a lot to make it much easier to write correct and safe code. They do require other infrastructure to work well, though - GC, defined runtime... –  Luaan 16 hours ago

Because it is more readable code.

For example (i love examples):

function myFunc(someInput:String) : OutputType
  if firstErrorCondition(someInput)
    throw new FirstConditionException
  if secondErrorCondition(someInput)
    throw new SecondConditionException
  if thirdErrorCondition(someInput)
    throw new ThirdConditionException
  // do some other fancy stuff and return value eventually

What if here we will return a value instead of throwing exceptions? Let me see:

function myFunc(someInput:String) : OutputType
  if firstErrorCondition(someInput)
    return -1
  if secondErrorCondition(someInput)
    return -2
  if thirdErrorCondition(someInput)
    return -3
  // do some other fancy stuff and return value eventually

Okay, it is still fine. But how clients code will looks?

OutputType result = myFunc(someInput)

That's a common part of it. Exceptions:

try {
  OutputType result = myFunc(someInput)
  //other operations
} catch (FirstErrorCondition e) {
  //do some exception handling
} catch (SecondErrorCondition e) {
  //do some magic
} catch (ThirdErrorCondition e) {
  //or just inform user that is a problem
} finally {
  //close everything and clean up after some doing
}

As a regular developer i can see what code is responsible for each part of error/exception.

OutputType result = myFunc(someInput)
switch(result) {
  case -1:
    //meh meh
  case -2:
    //meh meh
  case -3:
    //meh meh
  default:
    //and here we have a REGULAR code
}

Other plus of exceptions: It can be ommited in client code but it will throw exception eventually when issue occured. It will not be silient, buggy and unreadeable code.

share|improve this answer

I agree with remaining answer on one fact : That "exceptional return" does happen and needs to be handled.

But reason why exceptions exist is not that exceptional returns exist. It is possible to have "return values" for each of the possible error states, just like C does. The reason why exceptions are preferable to C-like error handling is that it is extremely rare that error from a function will be handled in immediate caller. It is much more common for error state to bubble up the stack until it gets into place where it can be reasonably handled. Also, single "handling" code will handle different method calls.

If you are using C-like error handling, you have to create extensive amount of code to do the bubbling and aggregation of errors all the way to the handler code. This requires discipline and rigor and drastically complicates return values from methods, where every possible exceptional return needs to have it's own value). Exceptions and infrastructure around them simply do all of this for you. And while I do agree exception handling too needs some level of discipline and rigor, it needs it much less.

share|improve this answer

Remember first you are solving problems. Imagine a simple solution, adding two numbers. You should do the following.

  1. Code the successful path in a test first. Ie. given 2, 2 return 4, given 1,2 return 3 and so on.
  2. Write the code to pass the test.
  3. Figure out ways to break things. Ie Given 1 raise exception Not enough args, Given A, 3 raise exception incorrect arg type.

That is the approach I always take. Its very TDD but it works for me and I have to say I find it quicker than any other approach. Exceptions are clean. And in a language like python there would be no coding required to raise most of them.. 'a'+2 raises an exception for free :-)

share|improve this answer

I find exceptions are cleaner for code style since I can wrap the code and deal with any errors in a specific location (the catch block), as opposed to littering my code with lots of if statements (if (result == -1)), to check for error conditions.

share|improve this answer

Because it's the easy way out.

Exceptions are, in part, an acknowledgement that error-handling is hard and while we can recover from exceptions, it's much easier not to.

Exceptions are the programmer's way of saying "I have this ideal situation that must be matched and I'll not bother spending more lines nor time handling situations that are not ." In essence, when you throw an exception, you're giving up:

} catch(e) {
    print("Give up."); // or something else akin to that
}
share|improve this answer
5  
Obvious troll is obvious. en.wikipedia.org/wiki/Invariant_%28computer_science%29 –  Aaronaught 17 hours ago
    
@Aaronaught, While silent downvotes don't help the site, comments which explain nothing is just as non-useful. Why do you say that this is a troll answer? –  Pacerier 15 hours ago
1  
@Pacerier, exceptions have nothing to do with giving up (and the paper you linked for this, has weak arguments and blanket statements). Exceptions are not "the easy way out", they are a mechanism introduced to the language, to address problems with signaling errors through error codes (they make things easier because that's what they were added to the language for). –  utnapistim 15 hours ago
1  
@utnapistim, The question is comparing exception handling against the other alternatives. And yes they make things easier when there's no need for reliability yet it's the easy way out when you get to high-reliability situations. See the links I've provided, especially blogs.msdn.com/b/oldnewthing/archive/2005/01/14/352949.aspx and joelonsoftware.com/items/2003/10/13.html –  Pacerier 15 hours ago
6  
@Pacerier: you say "easy way out" like it's a bad thing. A good programmer writes no more than necessary, and your answer doesn't even hint at why more complexity is appropriate. –  DougM 13 hours ago

Not the answer you're looking for? Browse other questions tagged or ask your own question.