102

Google's Go language has no exceptions as a design choice, and Linus of Linux fame has called exceptions crap. Why?

Trott
  • 66,479
  • 23
  • 173
  • 212
joemoe
  • 5,734
  • 10
  • 43
  • 60
  • 5
    Creator of ZeroMQ writes about how he thinks it was a mistake to write it in C++ (mostly because of the error handling) http://www.250bpm.com/blog:4 – serbaut Oct 20 '12 at 19:13
  • Go may not have exceptions, but it has "panics" that you can "recover" from (while deferred statements are still executed) and that provide non-local control flow... – Kerrek SB Mar 18 '17 at 22:59
  • 1
    Here's a nice article http://www.lighterra.com/papers/exceptionsharmful/ (Exception Handling Considered Harmful) – masterxilo Oct 16 '17 at 21:53
  • Afaics, [exceptions can be simulated in Go with significant boilerplate](https://github.com/keean/zenscript/issues/17#issuecomment-359338947), although this point may be more meaningful for transpiling from a syntax sugar than for writing the boilerplate manually. – Shelby Moore III Jan 22 '18 at 17:31

15 Answers15

98

Exceptions make it really easy to write code where an exception being thrown will break invariants and leave objects in an inconsistent state. They essentially force you to remember that most every statement you make can potentially throw, and handle that correctly. Doing so can be tricky and counter-intuitive.

Consider something like this as a simple example:

class Frobber
{
    int m_NumberOfFrobs;
    FrobManager m_FrobManager;

public:
    void Frob()
    {
        m_NumberOfFrobs++;

        m_FrobManager.HandleFrob(new FrobObject());
    }
};

Assuming the FrobManager will delete the FrobObject, this looks OK, right? Or maybe not... Imagine then if either FrobManager::HandleFrob() or operator new throws an exception. In this example, the increment of m_NumberOfFrobs does not get rolled back. Thus, anyone using this instance of Frobber is going to have a possibly corrupted object.

This example may seem stupid (ok, I had to stretch myself a bit to construct one :-)), but, the takeaway is that if a programmer isn't constantly thinking of exceptions, and making sure that every permutation of state gets rolled back whenever there are throws, you get into trouble this way.

As an example, you can think of it like you think of mutexes. Inside a critical section, you rely on several statements to make sure that data structures are not corrupted and that other threads can't see your intermediate values. If any one of those statements just randomly doesn't run, you end up in a world of pain. Now take away locks and concurrency, and think about each method like that. Think of each method as a transaction of permutations on object state, if you will. At the start of your method call, the object should be clean state, and at the end there should also be a clean state. In between, variable foo may be inconsistent with bar, but your code will eventually rectify that. What exceptions mean is that any one of your statements can interrupt you at any time. The onus is on you in each individual method to get it right and roll back when that happens, or order your operations so throws don't effect object state. If you get it wrong (and it's easy to make this kind of mistake), then the caller ends up seeing your intermediate values.

Methods like RAII, which C++ programmers love to mention as the ultimate solution to this problem, go a long way to protect against this. But they aren't a silver bullet. It will make sure you release resources on a throw, but doesn't free you from having to think about corruption of object state and callers seeing intermediate values. So, for a lot of people, it's easier to say, by fiat of coding style, no exceptions. If you restrict the kind of code you write, it's harder to introduce these bugs. If you don't, it's fairly easy to make a mistake.

Entire books have been written about exception safe coding in C++. Lots of experts have gotten it wrong. If it's really that complex and has so many nuances, maybe that's a good sign that you need to ignore that feature. :-)

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
asveikau
  • 39,039
  • 2
  • 53
  • 68
  • 10
    Interesting answer, however it does not reflect anything in my programming experience. So I guess it's either culture-specific (maybe more of a problem in Java or C++ than, say, Python) or domain-specific. – ddaa Nov 16 '09 at 10:24
  • 50
    Exceptions written in a managed language using a try-catch-finally pattern should never leave invalid state if they are written properly; since the finally block is guaranteed to be executed, objects can be deallocated there. The rest should be taken care of by variables going out of scope and garbage collection. – Robert Harvey Nov 17 '09 at 17:20
  • 9
    @ddaa The issue is definitely possible in Python. The result is typically a difficult to reproduce bug. Perhaps you've been especially meticulous, or lucky. But then, you are right that it's more of an issue in C++, where the most common bug from poor EH is a memory leak. I tried to emphasize that leaks aren't the most serious problem. @Robert GC will mitigate memory leaks, but I'm not sure managed code will free you from programmer error. In particular if someone is not paying attention to exception safety because they don't think it's a problem in their language, that's not a great sign. – asveikau Nov 17 '09 at 18:52
  • 1
    IMO, we could handle errors by return values, sometimes we have to use exceptions because the 3rd parties will throw exceptions --- Is there any advantages of exception over return value? – Baiyan Huang Sep 27 '10 at 01:09
  • 5
    @lzprgmr there certainly are: exceptions allow you to deal with diff. types of errors at diff. places in code. Dealing with a connection error might require a reconnection, but not in the middle of a deeply nested function. You want to bubble that up to the connection manager or something. Then dealing with return values forces you to check errors on each single call, and bubble that up manually (in the case of a connection reset error for ex.). Also, return values stack up in nested calls: func3 can return -1, func2 calls func3, returns -2 on his errors, -1 for func3's, etc.. – abourget May 20 '13 at 04:51
  • 5
    I was voting down, but I reversed that because this is a reason why exceptions are looked down upon. However in my opinion, almost any method or piece of code can fail. You cannot handle each error condition by introducing a return value for it. You will loose information about the error. Thinking that you can keep everything nicely synced by checking each and every statement and doing the cleaning up leads to very convoluted code - catching an error over multiple statements and cleaning up the one or two resources that are not GC'ed is much cleaner. – Maarten Bodewes May 05 '14 at 19:57
  • Seriously, if you want to bash Exceptions as a concept, don't use C++ to demonstrate the problem. We all know Exceptions in C++ are a PITA, but almost everything else in C++ is complicated too.Use something like Python, or Java. – Bastian Voigt Jun 05 '14 at 10:09
  • 1
    @owlstead: If code can return an error object whose type is independent of the "normal" return type, then code which notices that an error object has been returned will be able to get just as much information--if not more--about the error that occurred than would code that caught an exception. The real problems with exceptions are (1) existing frameworks offer no good way to deal with errors that occur while cleaning up from other errors; (2) existing frameworks offer no good way to distinguish an exception which escapes a method for reasons that method expects, and those which escape... – supercat Jul 03 '14 at 21:34
  • 1
    ...because they were thrown unexpectedly from within an inner method. – supercat Jul 03 '14 at 21:35
  • you're showing a case where you can't get strong guarantees automatically (RAII or not you'll need extra code) but how other methods would possibly solve the problem in a simpler and more elegant way? – a.lasram Aug 29 '15 at 04:17
  • 1
    Personal irritation here, but what on earth is "most every" supposed to mean? 'most' means 'more than half but not all', 'every' means 'all', so 'most every' means 'more than half but not all, but all' which is just plain gibberish. The word you are looking for is 'almost'. – Neutrino May 24 '16 at 09:49
  • 3
    I don't understand the argument "the increment of m_NumberOfFrobs does not get rolled back" and in general about invariants. In case we would use return value without exception what is the gain? Still "m_NumberOfFrobs does not get rolled back". To roll back m_NumberOfFrobs you have to catch exception or check return value. These two things seems to me equally bad or good for the purpose. And in case of invoking HandleFrob 10 times exception handling allows to avoid duplication of code. – robsosno Oct 09 '17 at 20:13
  • 1
    At least for a Java developer it's just natural that any call can throw exception. So it's not a hidden thing, it's the default assumption. Therefore, in your example, we just do the logical thing: incrementing m_NumberOfFrobs after the frob was successfully added to the manager. But you had to do the same in Go/Rust as well, because if you increment, and after that explicitly return with error, you got the same problem. – ddekany Jan 09 '21 at 02:56
  • 1
    Aren't exceptions just intended for debugging purposes? I find i can usually find specific memory related bugs much faster by letting my exceptions, throw up to main, handle them, and then close the program. I then take the output, and fix the problem. – ZeroPhase May 07 '21 at 17:51
  • 1
    That's a terrible and totally wrong example. First of all, you increment Frobcount before successfully adding a FrobObject. That's just bad programming. Second of all if new FrobObject throws an exception, your HandleFrob won't even execute, won't add anything (the object has to be created first before you add it to anything) so no inconsitent state. This is the type of thinking that falsely labels exception as "bad". – Walt Howard May 18 '21 at 18:39
52

The reason for Go not having exceptions is explained in the Go language design FAQ:

Exceptions are a similar story. A number of designs for exceptions have been proposed but each adds significant complexity to the language and run-time. By their very nature, exceptions span functions and perhaps even goroutines; they have wide-ranging implications. There is also concern about the effect they would have on the libraries. They are, by definition, exceptional yet experience with other languages that support them show they have profound effect on library and interface specification. It would be nice to find a design that allows them to be truly exceptional without encouraging common errors to turn into special control flow that requires every programmer to compensate.

Like generics, exceptions remain an open issue.

In other words, they haven't yet figured out how to support exceptions in Go in a way that they think is satisfactory. They are not saying that Exceptions are bad per se;

UPDATE - May 2012

The Go designers have now climbed down off the fence. Their FAQ now says this:

We believe that coupling exceptions to a control structure, as in the try-catch-finally idiom, results in convoluted code. It also tends to encourage programmers to label too many ordinary errors, such as failing to open a file, as exceptional.

Go takes a different approach. For plain error handling, Go's multi-value returns make it easy to report an error without overloading the return value. A canonical error type, coupled with Go's other features, makes error handling pleasant but quite different from that in other languages.

Go also has a couple of built-in functions to signal and recover from truly exceptional conditions. The recovery mechanism is executed only as part of a function's state being torn down after an error, which is sufficient to handle catastrophe but requires no extra control structures and, when used well, can result in clean error-handling code.

See the Defer, Panic, and Recover article for details.

So the short answer is that they can do it differently using multi-value return. (And they do have a form of exception handling anyway.)


... and Linus of Linux fame has called exceptions crap.

If you want to know why Linus thinks exceptions are crap, the best thing is to look for his writings on the topic. The only thing I've tracked down so far is this quote that is embedded in a couple of emails on C++:

"The whole C++ exception handling thing is fundamentally broken. It's especially broken for kernels."

You'll note that he's talking about C++ exceptions in particular, and not exceptions in general. (And C++ exceptions do apparently have some issues that make them tricky to use correctly.)

My conclusion is that Linus hasn't called exceptions (in general) "crap" at all!

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
31

Exceptions are not bad per se, but if you know they are going to happen a lot, they can be expensive in terms of performance.

The rule of thumb is that exceptions should flag exceptional conditions, and that you should not use them for control of program flow.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • 9
    @Robert: "you should not use them for control of program flow", I've not thought about it this way, new perspective for me :P +1 – o.k.w Nov 15 '09 at 00:53
  • 2
    It also really depends on the language. It's difficult to avoid exceptions if you're programming in Java for example. – Charles Salvia Nov 15 '09 at 00:56
  • 2
    @Charles: I think the point is that exceptions are appropriate in situations that indicate a bug, misconfigured system, or unreasonable inputs. Most Java library exceptions can be avoided in "normal workflow" code. – Artelius Nov 15 '09 at 01:17
  • 6
    they don't have to cost much. for example, you can implement a "try" that costs zero execution time, and have "throw" look up exception handlers in a table based on the caller addresses it sees on the stack... I would say that the biggest reasons not to use exceptions are not at all related to performance. – asveikau Nov 15 '09 at 02:21
  • Rephrased; the question clearly hints at using exceptions in general, or not using exceptions at all (they are crap or are not even in the language). Your answer only shows why exceptions are bad for performance when used for program control flow. – Maarten Bodewes May 05 '14 at 20:24
  • @owlstead: I don't have any opinion beyond that. – Robert Harvey May 05 '14 at 21:13
  • Of course you do - you're a developer :) But the point is that you're explaining when to use exceptions. And you're explaining it well. But is that what was asked? – Maarten Bodewes May 05 '14 at 21:29
  • @owlstead: Just realized that I answer this four and a half years ago. – Robert Harvey May 05 '14 at 21:31
  • Yeah, sorry, diggin' up worms. I got here when looking for specific questions / answers on exceptions. I do often do this, voting up and making alterations when necessary. Sometimes I vote down as well, in this case I thought it required an explanation, sorry to disturb you :) – Maarten Bodewes May 05 '14 at 21:34
  • The expensive cost comes in different coding style, and that the tracking code that makes try "cost-free" requires that some optimizations can't be performed. – Lothar Feb 04 '15 at 13:12
  • And when did you start hating Python ;) In Python, the idomatic way is often to use exceptions for flow control (e.g. getting a value from a dict). I don't agree with it BTW, but it should be noted that "exceptions should flag exceptional conditions, and that you should not use them for control of program flow" is very far from a universal opinion. – Paul Draper Oct 07 '15 at 15:00
  • @asveikau [more details](https://stackoverflow.com/questions/13835817/are-exceptions-in-c-really-slow) about the performance implications. – Shelby Moore III Jan 22 '18 at 03:27
  • Note that Python goes completely against this rule of thumb (this is meant as criticism of python). – martinkunev May 18 '21 at 10:35
29

I disagree with "only throw exceptions in an exceptional situation." While generally true, it's misleading. Exceptions are for error conditions (execution failures).

Regardless of the language you use, pick up a copy of Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition). The chapter on exception throwing is without peer. Some quotes from the first edition (the 2nd's at my work):

  • DO NOT return error codes.
  • Error codes can be easily ignored, and often are.
  • Exceptions are the primary means of reporting errors in frameworks.
  • A good rule of thumb is that if a method does not do what its name suggests, it should be considered a method-level failure, resulting in an exception.
  • DO NOT use exceptions for the normal flow of control, if possible.

There are pages of notes on the benefits of exceptions (API consistency, choice of location of error handling code, improved robustness, etc.) There's a section on performance that includes several patterns (Tester-Doer, Try-Parse).

Exceptions and exception handling are not bad. Like any other feature, they can be misused.

TrueWill
  • 25,132
  • 10
  • 101
  • 150
  • 5
    I have to disagree on that. I'm not against exceptions, and that book is a must have, however it's biased toward .NET development, and C#. –  Oct 12 '12 at 06:09
  • 3
    I know this is ancient, just wanted to comment that it seems there'd be a general style disagreement between the .NET type and the *nix type. All of the libraries I've used as a Linux dev use return codes, and *nix style guides I've read (like my company's and [Google's](https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Exceptions) for example) simply say "we don't do exceptions". Just think it's interesting. – jarvisteve Jul 18 '14 at 15:25
  • 1
    Frameworks should treat exceptions differently from end user applications. Frameworks don't have a way to deal with errors other than throwing an exception, consumer applications do. – 0x6C38 May 28 '16 at 03:01
  • 1
    BINGO. Exceptions are slightly more than just error conditions. They are any condition where your function cannot do its job, fulfill expectations. It has encountered exceptional circumstances. Should openfile() throw an exception if the file is missing? It depends on what was promised. If openfile() is allowed to create the file if it doesn't exist, no exception. – Walt Howard May 18 '21 at 18:46
11

From the perspective of golang, I guess not having exception handling keeps the compiling process simple and safe.

From the perspective of Linus, I understand that kernel code is ALL about corner cases. So it makes sense to refuse exceptions.

Exceptions make sense in code were it's okay to drop the current task on the floor, and where common case code has more importance than error handling. But they require code generation from the compiler.

For example, they are fine in most high-level, user-facing code, such as web and desktop application code.

ddaa
  • 52,890
  • 7
  • 50
  • 59
  • 1
    But what is true for kernel code is also true for long running native server processes. – Lothar Feb 04 '15 at 13:14
  • 3
    But high level languages are there to make programming by HUMANS easier, not to please the computer or the compiler. – Walt Howard May 18 '21 at 18:48
11

Exceptions in and of themselves are not "bad", it's the way that exceptions are sometimes handled that tends to be bad. There are several guidelines that can be applied when handling exceptions to help alleviate some of these issues. Some of these include (but are surely not limited to):

  1. Do not use exceptions to control program flow - i.e. do not rely on "catch" statements to change the flow of logic. Not only does this tend to hide various details around the logic, it can lead to poor performance.
  2. Do not throw exceptions from within a function when a returned "status" would make more sense - only throw exceptions in an exceptional situation. Creating exceptions is an expensive, performance-intensive operation. For example, if you call a method to open a file and that file does not exist, throw a "FileNotFound" exception. If you call a method that determines whether a customer account exists, return a boolean value, do not return a "CustomerNotFound" exception.
  3. When determining whether or not to handle an exception, do not use a "try...catch" clause unless you can do something useful with the exception. If you are not able to handle the exception, you should just let it bubble up the call stack. Otherwise, exceptions may get "swallowed" by the handler and the details will get lost (unless you rethrow the exception).
Jeff Bramwell
  • 990
  • 8
  • 16
  • 4
    Returning status is a tricky thing. I've seen far too much code that has a GetCustomer method returning a Customer entity on success or null on failure. In multiple cases the calling code never checked the result, but immediately accessed the Customer. This worked most of the time... – TrueWill Nov 15 '09 at 03:47
  • 3
    But if GetCustomer throws an exception instead of returning null, the client code still needs to handle the exception. Whether it's by checking for null or by handling exceptions, the responsibility lies with the client code - if it doesn't do what things properly, then either way sooner or later something will explode. – Chris Nov 18 '09 at 22:01
  • 2
    @TrueWill Languages that support templates/generics solve this by returning an `Option` instead of `null` nowadays. Just got introduced in Java 8 for instance, taking a hint from Guava (and others). – Maarten Bodewes May 05 '14 at 19:46
  • @owlstead Yep. Love the maybe monad. That's a good way to go if your language supports it and offers pattern matching. – TrueWill May 06 '14 at 14:13
  • @owlstead Again, what Chris said still holds strong for that - the user has to remember to call the .orElse(defaultObject) function, or whichever idiom the language in question has decided. At the end of the day it's ultimately the programmers that are the problem, rather than the error handling method. – Pharap Jul 19 '14 at 06:17
  • 1
    This is what confuses people about exceptions. You should only return values from functions when the value is what the function was supposed to get for you, not some out of band value that means "error". How are you supposed to return an error code from a function that returns a string? It's so simple, that it's too simple for people; If your function cannot do its job, throw. That's it. – Walt Howard May 18 '21 at 18:50
9

Typical arguments are that there's no way to tell what exceptions will come out of a particular piece of code (depending on language) and that they are too much like gotos, making it difficult to mentally trace execution.

http://www.joelonsoftware.com/items/2003/10/13.html

There is definitely no consensus on this issue. I would say that from the point of view of a hard-core C programmer like Linus, exceptions are definitely a bad idea. A typical Java programmer is in a vastly different situation, though.

Tim Sylvester
  • 22,897
  • 2
  • 80
  • 94
  • 2
    C code has exceptions sort of, just in a different way. You need to wrap every call to a non trivial function in ifs which makes using that language a headache! – RCIX Nov 15 '09 at 02:30
  • 1
    There's also the `setjmp`/`longjmp` stuff, which is pretty bad. – Tim Sylvester Nov 15 '09 at 02:51
  • 9
    Do you really want to take the advice of a man who values Duct Tape programmers and who does not believe that unit tests are necessary? http://www.joelonsoftware.com/items/2009/09/23.html – TrueWill Nov 15 '09 at 03:52
  • 5
    This is classic mistake (or cheat) in a discussion where arguments on the subject are replaced with personality references. That usually a sign of degenerating discussion. – Petr Gladkikh Apr 13 '12 at 11:13
  • 1
    @PetrGladkikh The discussion **started** with the OP referring to Linus's opinion ... that cheat is known as the fallacy of appeal to authority. The discussion can only go uphill from there, and it's no "cheat" to answer the question of why Linus doesn't like exceptions by referring to his personality. – Jim Balter Aug 04 '12 at 22:08
  • @PetrGladkikh This is not a discussion on exception handling per se, it is asking for reasons why exceptions are thought of as bad structures by people, so Joel's explanation is as good as any - even if you disagree with him (and I certainly do, but +1 none-the-less). – Maarten Bodewes May 05 '14 at 20:50
  • 1
    In addition to @TrueWill's comment, I'd like to point out that Linus is not against the use of gotos, so his reasons for disliking exceptions is probably completely unrelated to any confusion regarding the tracing of execution. – Pharap Jul 19 '14 at 05:54
  • I actually tend to agree with Joel in that article on Duct Tape programmers, but only to an extent. Yes, it is very important to ship a product, and to actually get something done, which is the ultimate point of the article. But, certain things that he mentioned seem quite unreasonable, such as not using templates or C++. I can see not using unit tests because MANY successful projects have gone without unit tests, and they DO take quite a bit of time. On the other hand, if you have a HUGE project, then unit tests will probably save you more time than they take to write. – SeanRamey Nov 20 '17 at 16:25
  • Linus may not think exceptions are appropriate but they never are if your code base has already been written without exceptions in mind. You need auto-destructing variables if you use exceptions in C and C++. Even with C++ you need to use smart-pointers for non-stack resources (items created with new on the heap). Exceptions are made WAY overcomplicated. You only need ONE exception class for your application and it must contain all the relevant information about the "error". – Walt Howard May 18 '21 at 18:55
8

Exceptions aren't bad. They fit in well with C++'s RAII model, which is the most elegant thing about C++. If you have a bunch of code already that's not exception safe, then they're bad in that context. If you're writing really low level software, like the linux OS, then they're bad. If you like littering your code with a bunch of error return checks, then they not helpful. If you don't have a plan for resource control when an exception is thrown (that C++ destructors provides) then they're bad.

paul
  • 81
  • 1
5

A great use-case for exceptions is thus....

Say you are on a project and every controller (around 20 different major ones) extends a single superclass controller with an action method. Then every controller does a bunch of stuff different from each other calling objects B, C, D in one case and F, G, D in another case. Exceptions come to the rescue here in many cases where there was tons of return code and EVERY controller was handling it differently. I whacked all that code, threw the proper exception from "D", caught it in the superclass controller action method and now all our controllers are consistent. Previously D was returning null for MULTIPLE different error cases that we want to tell the end-user about but couldn't and I didn't want to turn the StreamResponse into a nasty ErrorOrStreamResponse object (mixing a data structure with errors in my opinion is a bad smell and I see lots of code return a "Stream" or other type of entity with error info embedded in it(it should really be the function returns the success structure OR the error structure which I can do with exceptions vs. return codes)....though the C# way of multiple responses is something I might consider sometimes though in many cases, the exception can skip a whole lot of layers(layers that I don't need to clean up resources on either).

yes, we have to worry about each level and any resource cleanup/leaks but in general none of our controllers had any resources to clean up after.

thank god we had exceptions or I would have been in for a huge refactor and wasted too much time on something that should be a simple programming problem.

Dean Hiller
  • 19,235
  • 25
  • 129
  • 212
  • 1
    +1 Easily one of the best arguments for using exceptions that I have read. Could have used more detailed examples (i.e. a UML diagram, some pseudocode or some actual code) but the point about making subclasses perform consistently is a good one. Also, the fact your evidence is anecdotal shows that exceptions are useful in real situations, and usefulness is the main purpose of any language feature. – Pharap Jul 19 '14 at 06:33
  • just as an addition, if you are in scala, you can instead return Try[ResponseType] which represents an exception or actual response. You can then follow the same pattern I elude to above without actual exceptions other than they are put into the try. Then it is like every method you have returns 1+n response types which I think is needed. We however in scala return Future[response] which work much like the Try but can help with more asynchronous programming. – Dean Hiller Mar 16 '15 at 17:19
2

Theoretically they are really bad. In perfect mathematical world you cannot get exception situations. Look at the functional languages, they have no side effects, so they virtually do not have source for unexceptional situations.

But, reality is another story. We always have situations that are "unexpected". This is why we need exceptions.

I think we can think of exceptions as of syntax sugar for ExceptionSituationObserver. You just get notifications of exceptions. Nothing more.

With Go, I think they will introduce something that will deal with "unexpected" situations. I can guess that they will try to make it sound less destructive as exceptions and more as application logic. But this is just my guess.

Mike Chaliy
  • 25,801
  • 18
  • 67
  • 105
  • 2
    "Look at the functional languages, they have no side effects, so they virtually do not have source for unexceptional situations." That is a gross overstatement. – Stephen C Nov 15 '09 at 02:31
  • Could you please elaborate on this? – Mike Chaliy Nov 15 '09 at 12:15
  • 3
    What's 5/0 in math? Arcsin(200)? Sqrt(-1)? Math has loads of exceptional situations. – Robert Fraser Mar 27 '10 at 10:56
  • 3
    This is not execptional situatuations... they just have no meaning... and because of that could be implemented as exceptions... but also could be implemented as vialations of preconditions.. so its depends on technical implementation. – Mike Chaliy Mar 27 '10 at 17:43
  • 3
    @MikeChaliy - I'm sorry, but that is just sophistry. You can apply that kind of reasoning to say that there are NO exception situations in anything, EVER. In reality, mathematical expressions that have no meaning (or that have no definite value) ARE exceptional. This doesn't mean that they need to be dealt with by throwing and catching exceptions ... but if you don't do that you either need *special* values (like Inf and Nan) or operations that return multiple values. In short, these cases *require* som kind of special treatment. – Stephen C Apr 16 '13 at 10:41
  • Our conversation started 3 years ago :). Anyway, "some kind of special treatment" that was exactly my point in starting post. – Mike Chaliy Apr 16 '13 at 12:51
  • 3
    Computers are state machines. Not a perfect math world. – Arunav Sanyal Oct 12 '16 at 00:21
  • @RobertFraser: that's exactly why you have got NaNs in floating-point arithmetics. – shuhalo May 12 '21 at 03:47
1

The exception-handling paradigm of C++, which forms a partial basis for that of Java, and in turn .net, introduces some good concepts, but also has some severe limitations. One of the key design intentions of exception handling is to allow methods to ensure that they will either satisfy their post-conditions or throw an exception, and also ensure that any cleanup which needs to happen before a method can exit, will happen. Unfortunately, the exception-handling paradigms of C++, Java, and .net all fail to provide any good means of handling the situation where unexpected factors prevent the expected cleanup from being performed. This in turn means that one must either risk having everything come to a screeching halt if something unexpected happens (the C++ approach to handling an exception occurs during stack unwinding), accept the possibility that a condition which cannot be resolved due to a problem that occurred during stack-unwinding cleanup will be mistaken for one which can be resolved (and could have been, had the cleanup succeeded), or accept the possibility that an unresolvable problem whose stack-unwinding cleanup triggers an exception that would typically be resolvable, might go unnoticed as code which handles the latter problem declares it "resolved".

Even if exception handling would generally be good, it's not unreasonable to regard as unacceptable an exception-handling paradigm that fails to provide a good means for handling problems that occur when cleaning up after other problems. That isn't to say that a framework couldn't be designed with an exception-handling paradigm that could ensure sensible behavior even in multiple-failure scenarios, but none of the top languages or frameworks can as yet do so.

supercat
  • 77,689
  • 9
  • 166
  • 211
1

I havent read all of the other answers, so this ma yhave already been mentioned, but one criticism is that they cause programs to break in long chains, making it difficult to track down errors when debugging the code. For example, if Foo() calls Bar() which calls Wah() which calls ToString() then accidentily pushing the wrong data into ToString() ends up looking like an error in Foo(), an almost completely unrelated function.

kingfrito_5005
  • 611
  • 5
  • 15
  • 1
    At least in Java you will have stack trace for each exception that will show the whole call chain, with the ToString() in it. – ddekany Jan 09 '21 at 03:02
  • You can add stack tracing to C++. Use Google. Personally writing one line like: string data = Socket(TCP).Connect("75.32.44.23").ReadAll() If far more readable than SOCKET s = socket(TCP); if (if s == -1) return errono; int rval = s.connect("75.32.44.23"); if (rval == -1) return errno; char buffer[1024]; int rval = s.read(sizeof(buffer), buffer); if (rval == -1) return errno; return buffer; <--- error, cant return stack based buffer. – Walt Howard May 18 '21 at 19:03
0

For me the issue is very simple. Many programmers use exception handler inappropriately. More language resource is better. Be capable to handle exceptions is good. One example of bad use is a value that must be integer not be verified, or another input that may divide and not be checked for division of zero... exception handling may be an easy way to avoid more work and hard thinking, the programmer may want to do a dirty shortcut and apply an exception handling... The statement: "a professional code NEVER fails" might be illusory, if some of the issues processed by the algorithm are uncertain by its own nature. Perhaps in the unknown situations by nature is good come into play the exception handler. Good programming practices are a matter of debate.

iuri
  • 1
  • The issue isn't (or shouldn't be) whether code can fail--a bigger issue is the extent to which, if the code does fail, one cares about the particulars. If one tries to load a document and one of the "read data" methods fails, one often doesn't really care which one, since the effect is the same regardless: the document can't be loaded. Conceptually, exception handling should be good for that. The problem is that the exception-handling paradigms of .NET and Java don't provide any nice way of distinguishing "boring" exceptions that should be lumped together, from those that shouldn't. – supercat Sep 13 '13 at 15:28
-1
  • Exception not being handled is generally bad.
  • Exception handled badly is bad (of course).
  • The 'goodness/badness' of exception handling depends on the context/scope and the appropriateness, and not for the sake of doing it.
o.k.w
  • 25,490
  • 6
  • 66
  • 63
-1

Okay, boring answer here. I guess it depends on the language really. Where an exception can leave allocated resources behind, they should be avoided. In scripting languages they just desert or overjump parts of the application flow. That's dislikable in itself, yet escaping near-fatal errors with exceptions is an acceptable idea.

For error-signaling I generally prefer error signals. All depends on the API, use case and severity, or if logging suffices. Also I'm trying to redefine the behaviour and throw Phonebooks() instead. The idea being that "Exceptions" are often dead ends, but a "Phonebook" contains helpful information on error recovery or alternative execution routes. (Not found a good use case yet, but keep trying.)

mario
  • 144,265
  • 20
  • 237
  • 291