Why have many programmers moved to using exception handling for input or output? For these programmers, what is the motivation behind this decision?
-
13The abundance of C programmers and projects in C disagree with your claims of "almost all"– whatsisnameCommented Apr 23, 2015 at 3:48
-
3Java programmers don't get a choice!– James AndersonCommented Apr 23, 2015 at 6:35
-
3"almost all programmers, in almost all cases" - are you begging for downvotes?– Doc BrownCommented Apr 23, 2015 at 6:45
-
1Survival of the fittest. Exceptions work better than the alternative.– Mason WheelerCommented Apr 23, 2015 at 10:17
-
2Damon, 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.– durron597Commented Apr 23, 2015 at 13:22
7 Answers
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.
- Premature end-of-line termination, syntax error or any number of validation error conditions,
- Inputs are too long or large to reasonably accomodate,
- Keyboard gets unplugged,
- 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.
-
"Because input and output are unreliable" does not explain why exceptions are used instead of error-codes. As such, I believe I have a better explanation (despite the -15 downvotes) at programmers.stackexchange.com/a/279911/24257 .– PacerierCommented Apr 24, 2015 at 13:24
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).
-
1Not 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...– LuaanCommented Apr 23, 2015 at 8:40
-
1@utnapistim, This is an unbalanced comparison. If you wish to weigh the use case whereby we have multiple error codes, you must weigh it against the equivalent use case whereby we have multiple exception paths, as can be seen in the long snippet in stackoverflow.com/a/315967/632951 . If you are going to weigh the "catch-all" —
} catch(e) { /* handle all */ }
, then you must weigh it against the two-state errorcode0
and1
which doesn't useswitch
.– PacerierCommented Apr 24, 2015 at 13:16
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.
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.
Remember first you are solving problems. Imagine a simple solution, adding two numbers. You should do the following.
- Code the successful path in a test first. Ie. given 2, 2 return 4, given 1,2 return 3 and so on.
- Write the code to pass the test.
- 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 :-)
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.
Behavioral Economics #101: because it's the easier way.
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 do a "catch-all" type of exception handling, you're giving up:
} catch(e) {
print("Don't even know what error it is but **there's an error**. Exit / Retry.");
}
(Besides "catch-all" exceptions, there's also the "one-by-one" longform style which is the exception rather than the norm but not what folks are saying when they say "exception-handling".)
For adjunct reading, see https://en.wikipedia.org/wiki/Structured_programming#Exception_handling
-
5Obvious troll is obvious. en.wikipedia.org/wiki/Invariant_%28computer_science%29 Commented Apr 23, 2015 at 8:26
-
1@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?– PacerierCommented Apr 23, 2015 at 10:07
-
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). Commented Apr 23, 2015 at 10:08
-
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– PacerierCommented Apr 23, 2015 at 10:10
-
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.– DougMCommented Apr 23, 2015 at 12:23