243

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 ...


228

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 ...


177

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 ...


147

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 ...


144

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


135

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 ...


130

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 ...


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 ...


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.


81

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(...


79

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 should ...


76

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 ...


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.


67

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 ...


66

This is a good question that professional developers have to consider carefully. The guideline to follow is that exceptions are called exceptions because they are exceptional. If a condition can be reasonably expected then it should not be signaled with an exception. Let me give you a germane example from real code. I wrote the code which does overload ...


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

This code: try: do_something() except Exception: log_error() is dangerous. Not because you caught a generic Exception but because you suppressed the exception without doing any recovery or halting the system. Now the system is in an undefined state. It might be about to corrupt the database, format the hard drive, or send the president threatening ...


61

You want to throw an exception as soon as possible because that makes it easier to find the cause. For example, consider a method that could fail with certain arguments. If you validate the arguments and fail at the very beginning of the method, you immediately know the error is in the calling code. If you wait until the arguments are needed before failing, ...


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

Exceptions should be allowed to crash the system if the system has been left in an unrecoverable undefined state. If you can't put the system back in a defined state that ensures data integrity and security then you crash so the system can be rebooted into that defined state. Whenever you catch an exception you're taking responsibility for doing all that ...


58

These are two different questions. Should you accept null? That depends on your general policy about null in the code base. In my opinion, banning null everywhere except where explicitly documented is a very good practice, but it's even better practice to stick to the convention your code base already has. Should you accept the empty collection? In my ...


55

The main point of testing the exception message content is to make sure the right exception is thrown. There may be multiple reasons for which payForCart() throws a PaymentException. So it's not about the exact wording, but about whether it says "Cannot pay for ids A9dr6L, status is not WAITING" and not "Cannot pay for ids A9dr6L, balance insufficient". ...


53

I agree with Ewan's answer but want to add a specific reasoning. You are dealing with mathematical operations, so it might be a good advice to stick with the same mathematical definitions. From a mathematical standpoint the number of r-sets of an n-set (i.e. nCr) is well defined for all r > n >= 0. It is zero. Therefore returning an empty set would be the ...


52

If the core of your question is this... If some client code passes an argument whose value is invalid for the thing that my data structure is modeling, should I reject the value or convert it to something sensible? ...then my general answer would be "reject", because this will help draw attention to potential bugs in the client code that are actually ...


52

we did not know what to anticipate, while the behavior would be the same for all, e.g. log and continue with execution. To me, this is your major problem. If an exception occurs and you don't know how to handle it, you should not continue with execution because you don't know what state your system is in. Just pass it up to the next level and let that ...


49

Why is it that many common exceptions from system components do not contain useful details? In my experience, there are a number of reasons that exceptions do not contain useful information. I expect that these sorts of reasons would also apply to system components - but I don't know for sure. Security focused people see exceptions as a source of ...


49

But imagine that is some specific component we do know the best course of actions for a caller. This almost always fails for at least one of your callers, for which this behaviour is incredibly irritating. Don't assume you know best. Tell your users what's happening, not what you assume they should do about it. In many cases it's already clear what a sane ...


47

Is this a good way of handling exceptions? No, I think this is pretty bad practice.  Throwing an exception vs. returning a value is a fundamental change in the API, changing the method's signature, and making the method behave quite differently from an interface perspective. In general, when we design classes and their APIs, we should consider that ...


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