206

Exceptions do not contain useful details because the concept of exceptions has not matured yet enough within the software engineering discipline, so many programmers do not understand them fully, and therefore they do not treat them properly. Yes, IndexOutOfRangeException should contain the precise index that was out of range, as well as the range that was ...


175

Utility methods should not throw on empty collections. Your API clients would hate you for it. A collection can be empty; a "collection-that-must-not-be-empty" is conceptually a much more difficult thing to work with. Transforming an empty collection has an obvious outcome: the empty collection. (You may even save some garbage by returning the parameter ...


172

Silent But Deadly When writing enterprise software, you will eventually learn an essential truth: the worst bug in the world is not one that causes your program to crash. The worst bug in the world is one which causes your program to silently produce a wrong answer that goes unnoticed but eventually produces a massive negative effect (with severe financial ...


148

It depends on whether you can deal with the exceptions that can be raised at this point or not. If you can handle the exceptions locally you should, and it is better to handle the error as close to where it is raised as possible. If you can't handle them locally then just having a try / finally block is perfectly reasonable - assuming there's some code you ...


145

Return an Empty Set I would expect an empty set because: There are 0 combinations of 4 numbers from the set of 3 when i can only use each number once


139

As a general principle, don't catch exceptions unless you know what to do with them. If MethodC throws an exception, but MethodB has no useful way to handle it, then it should allow the exception to propagate up to MethodA. The only reasons why a method should have a catch and rethrow mechanism are: You want to convert one exception to a different one ...


131

but crashing your client's software is still not a good thing It most certainly is a good thing. You want anything that leaves the system in an undefined state to stop the system because an undefined system can do nasty things like corrupt data, format the hard drive, and send the president threatening emails. If you cannot recover and put the system back ...


123

BEWARE! Assertions are removed at runtime unless you explicitly specify to "enable assertions" when compiling your code. Java Assertions are not to be used on production code and should be restricted to private methods (see Exception vs Assertion), since private methods are expected to be known and used only by the developers. Also assert will throw ...


121

In my experience, its best to throw exceptions at the point where the errors occur. You do this because it's the point where you know the most about why the exception was triggered. As the exception unwinds back up the layers, catching and rethrowing is a good way to add additional context to the exception. This can mean throwing a different type of ...


114

The use case that exceptions were designed for is "I just encountered a situation that I cannot deal with properly at this point, because I don't have enough context to handle it, but the routine that called me (or something further up the call stack) ought to know how to handle it." The secondary use case is "I just encountered a serious error, and right ...


113

There's a detailed discussion of this on Ward's Wiki. Generally, the use of exceptions for control flow is an anti-pattern, with many notable situation - and language-specific (see for example Python) cough exceptions cough. As a quick summary for why, generally, it's an anti-pattern: Exceptions are, in essence, sophisticated GOTO statements Programming ...


109

The benefit is that your "custom" exception has an error message that's meaningful to anyone calling this function without knowing how it's implemented (which in the future might be you!). Granted, in this case they'd probably be able to guess what the "standard" exception meant, but you're still making it clear that they violated your contract, rather than ...


100

I agree with Ixrec's answer. However, you might want to consider a third alternative: making the function idempotent. In other words, return early instead of throwing an ArgumentException. This is often preferable if you would otherwise be forced to check if it has already been loaded before calling LoadMaterial every time. The fewer preconditions you ...


88

Exceptions were invented to help make error handling easier with less code clutter. You should use them in cases when they make error handling easier with less code clutter. This "exceptions only for exceptional circumstances" business stems from a time when exception handling was deemed an unacceptable performance hit. That's no longer the case in the ...


86

There are 3 reasons for this: The cost of checking for overflows (for every single arithmetic operation) at run-time is excessive. The complexity of proving that an overflow check can be omitted at compile-time is excessive. In some cases (e.g. CRC calculations, big number libraries, etc) "wrap on overflow" is more convenient for programmers.


80

When in doubt, ask someone else. Your example function has a very similar one in Python: itertools.combinations. Let's see how it works: >>> import itertools >>> input = [1, 2, 3, 4, 5] >>> list(itertools.combinations(input, 2)) [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)] >>> list(...


78

In Python in particular, it is usually considered better practice to catch the exception. It tends to get called Easier to Ask for Forgiveness than Permission (EAFP), compared to Look Before You Leap (LBYL). There are cases where LBYL will give you subtle bugs in some cases. However, do be careful of bare except: statements as well as overbroad except ...


76

Why would you postpone throwing the exception? If you know that the object can't properly instantiate with the given parameters, then you should definitely throw an exception. Otherwise, somebody might test your object for null, which it won't be, and could assume everything went as expected. There are a lot of things that can be done to your object ...


75

Yes, your colleague is right: that is bad code. If an error can be handled locally, then it should be handled immediately. An exception should not be thrown and then handled immediately. This is much cleaner then your version (the getValueByKey() method is removed) : public String getByKey(String key) { if (valuesFromDatabase.containsKey(key)) { ...


73

The problem with this approach is that while exceptions never get thrown (and thus, the application never crashes due to uncaught exceptions), the results returned are not necessarily correct, and the user may never know that there is a problem with the data (or what that problem is and how to correct it). In order for the results to be correct and ...


72

When should an exception be thrown? When it comes to code, I think that following explanation is very helpful: An exception is when a member fails to complete the task it is supposed to perform as indicated by its name. (Jeffry Richter, CLR via C#) Why is it helpful? It suggests that it depends on the context when something should be handled as an ...


71

In layman's terms: If there is an error, you should raise an exception. That may involve doing things in steps instead of in a single chained call in order to know exactly where the error happened. If there is no error but the resulting set is empty, don't raise an exception, return the empty set. An empty set is a valid set.


70

You have to distinguish between return values and errors. A return value is one of many possible outcomes of a computation. An error is an unexpected situation which needs to be reported to the caller. A module may indicate that an error occurred with a special return value or it throws an exception because an error was not expected. That errors occur ...


69

In .NET, it is common practice to avoid the overuse of Exceptions. One argument is performance: in .NET, throwing an exception is computationally expensive. Another reason to avoid their overuse is that it can be very difficult to read code that relies too much on them. Joel Spolsky's blog entry does a good job of describing the issue. At the heart of the ...


66

If a language inherently supports exceptions, then it is preferred to throw exceptions and the clients can catch the exception if they do not want it to result in a failure. In fact, the clients of your code expect exceptions and will run into many bugs because they will not be checking the return values. There are quite a few advantages to using exceptions ...


64

Who says it's a bad tradeoff?! I run all of my production apps with overflow checking enabled. This is a C# compiler option. I actually benchmarked this and I was not able to determine the difference. The cost of accessing the database to generate (non-toy) HTML overshadows the overflow checking costs. I do appreciate the fact that I know that no ...


63

In my mind, the biggest argument is the difference in what happens when the programmer makes an error. Forgetting to handle an error is a very common and easy mistake to make. If you return error codes, it is possible to silently ignore an error. For example, if malloc fails, it returns NULL and sets the global errno. So correct code should do void* ...


61

It really depends on how often you think the exception is going to be thrown. Both approaches are, in my opinion, equally valid, at least in terms of readability and pythonic-ness. But if 90% of your objects do not have the attribute bar you'll notice a distinct performance difference between the two approaches: >>> import timeit >>> def ...


60

I don't need the catch block. But you do need to catch. The behavior of your code with a catch block is to catch any exception, and then forget that it happened. So any exception that tries to pass through will stop, and your code will basically pretend that the try block executed successfully. So you want a naked try block to act like it catches an ...


59

They don't need to be errors at all. The fact that the page is not there may be just an interesting fact rather than an actual error. They seem to get used as errors almost all the time, I admit. But sometimes they're used to break out of loops, or let you know that a string is not a valid number. They can be used to hold and return vast amounts of ...


Only top voted, non community-wiki answers of a minimum length are eligible