6 ms·
Everyone here seems to agree that "exceptions are for exceptional conditions". The problem is that when you get down to details, there is disagreement about wha
by beagle3 13y ago
Everyone here seems to agree that "exceptions are for exceptional conditions". The problem is that when you get down to details, there is disagreement about what exactly is an "exceptional condition".
e.g. - you are trying to open a file for reading. The file does not exist. Is this exceptional? That depends on context, but the function that opens the file, being in an independent library, is usually designed without this context.
If it does throw an exception, some people complain that "of course it'e expected that file won't be there sometimes! that's not exceptional".
If it doesn't throw an exception, some people complain that "we tried to open a file, but didn't succeed, of course that's an exception". But if you want to avoid an exception in this case, you'll need to check for existence before opening (LBYL "look-before-you-leap"), and get into a race condition (TOCTOU "time-of-check,time-of-use"), which is really bad.
So it very often happens that you are forced by your ecosystem to use exceptions for normal control flow. Claims that you can only use it for "exceptional / unexpected" tend to be incompatible with a project in which you do not develop/control all of the library you use to your strict standard of exceptionalness.
- wvenable 13y ago> you are trying to open a file for reading. The file does not exist. Is this exceptional? It's actually handy to have an API that includes both situations. For example, parse and tryParse in C#. Parse will trigger an exception if it fails but tryParse will not. When used in your code, this actually documents what the programmer is expected. If an open and tryOpen operations existed, you would know whether or not the programmer expects the file to exist or not.
- protomyth 13y agoGoing one step further on the file example, I had a college professor who wrote a function read from a file that had no end except an exception thrown by the read because the file was at its end[1]. He said the end-of-file was an exceptional circumstance for a function that expected to read and process a line. I doubt anyone would say end-of-file is unexpected, but I am not sure I would say it was exceptional. 1) something like this (it has been 20yrs) init data structure S open file A loop read line from A process line and add to S next catch EOF close A return S catch file-not-found return empty S any mistakes are my memory not my old professor
- twic 13y agoIn Java, everyone would tell you this is wrong. In Python, this is the normal way to end an iteration (specifically, throwing StopIteration). It's not a huge leap to see a stream as an iteration over bytes. So, what's considered exceptional seems somewhat culturally dependent.
- comex 13y agoNote that in Python you usually use the syntactic sugar of for loops rather than interacting with StopIteration manually.
- twic 13y agoTrue! I should have made that clearer. The only time you need to think about StopIteration is if you're consuming from an iterator in some unusual way (eg writing a "get me the single item which is in this iterator, or blow up if there are zero or more than one" function) or if you're writing an iterator which is not built out of building blocks which already know how to stop an iteration. So, not often.
- randomtask 13y agoIt's possible for a library to return an error to indicate that a file is not found when you try and open a non-existent file. Then it's possible for a function that calls the open file function to decide whether that error should be translated into an exception i.e. should that file being missing break out of the current execution? There's no race condition there. I don't think anyone reasonably expects a library to know the context of the file being opened and its importance in the logic of the rest of the program.
- bjourne 13y agoThe rule is that all functions should return a valid result or not return at all. Aka the Samurai Principle: http://c2.com/cgi/wiki?SamuraiPrinciple http://c2.com/cgi/wiki?SamuraiPrinciple However, an important point is that a "valid result" maybe a status indicating what went wrong. For example, a function that reads an http url may return (OK, 200), (NOT_FOUND, 404), (REDIRECT, 301) and so on. But in addition to that, the function may also throw an exception if a dns lookup error occurred for example. Opening files on the other hand, can fail unexpectedly for a billion different reasons. Most of which an opening function can't detect or do anything about and therefore can't return a valid result if they occur. Therefore it must throw an exception.
- beagle3 13y ago> the function may also throw an exception if a dns lookup error occurred for example. What's wrong with (DNS Lookup Failure, -17), as long as it is documented? why doesn't 404 NOT_FOUND merit an exception, yet a DNS lookup failure does? (I can argue both ways, I'm just trying to point that there's no clear criterion) > therefore can't return a valid result if they occur. Therefore it must throw an exception. But open() in C does return a valid result on any of those billion reasons: (fd -1, errno reason). Yes, errno is returned in a global variable, but it is still a return from the open() call. Therefore, exceptions are never needed according to your logic?
- bjourne 13y ago>> the function may also throw an exception if a dns lookup error occurred for example. > What's wrong with (DNS Lookup Failure, -17), as long as it is documented? why doesn't 404 NOT_FOUND merit an exception, yet a DNS lookup failure does? Because then every function that could potentially cause a dns lookup failure needs to have that error code documented. Then ask yourself this, what's wrong with having (Out of Memory Failure, -1234) in addition to DNS Lookup Failure and HTTP Status codes? Think of yourself as a http function. You know about the http protocol and therefore from your perspective a 404 NOT_FOUND is a valid result. However, you do not know about DNS lookups or memory allocation therefore if a problem occurs in those areas it is exceptional -> exception. On the other hand, if you were a memory allocator function then returning out of memory instead of an address to the allocated memory would be fine. Because memory handling is your job. > But open() in C does return a valid result on any of those billion reasons: (fd -1, errno reason). Syntactically valid, but not semantically as -1 isn't a valid file descriptor.
- mindslight 13y agoVague value judgments ("only for exceptional conditions") are the inevitable result of a failure to reason. The semantic function of exceptions is just a way for summing additional values onto the return type of a function because it has results that are not contained within the primary type. In this way, they are a more general and better typed version of NULL (which has it's places - contrary to the modern dogma, these sort of features are needed due to inherent complexity). The standard ways of attempting to avoid this are to either use sentinel values that exist in your standard return type like fd == -1 for an error (thereby making your program less typed), or to create a top-level sum type for every aggregated function return type (cluttering your program with nominal types). Multiple values make the most sense, but those are ad-hoc product types, so you're eschewing the type system in favor of informal invariants. The syntactic function of exceptions is to avoid constantly repeating (check for error, return error), which often leads to the poor practices of ignoring errors or calling a global exit(). One goal of programming languages is to automate, so it makes sense to capture this oft-repeated pattern. But problems arise when people end up forgetting that every function can have a possible return immediately following it. It seems some syntactic middleground is needed to signal the complete return type of a function definition, and the possibility that a given function call may quick-return. Honestly (and I hate to say it), but Java probably started down the right track with checked exceptions, but being a B&D language it ended up being waaaay too verbose. And lacking a way to aggregate types along anything but the baked-in hierarchy, people fell into using generic and uninformative 'throws Exception'. And open types make it so there's little point trying to enumerate exhaustive causes. But that doesn't mean that one can't start with the idea of non-silent but syntactically lightweight exceptions and come up with something that avoids a lot of the pitfalls.
- untothebreach 13y agoIt seems to be a pattern in Python APIs to allow the caller to decide if a given function call should throw an exception when an error occurs. For example, a = some_dict['nonexistent_key'] would raise a KeyError, while a = some_dict.get('nonexistent_key', 'DEFAULT') would return 'DEFAULT' instead.