Tag Info

Hot answers tagged

172

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


160

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


114

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


106

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


97

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


92

Well, it's pretty simple: not all exceptions are bugs (and similarly, not all bugs manifest themselves as exceptions). As example of an exception that's not a bug, if you're reading a file from a USB drive and someone yanks the drive out of the socket. That's going to raise an exception (in most languages that support exceptions, that is). But it's not a ...


89

The problem is that because in theory any object can be a null and toss an exception when you attempt to use it, your object-oriented code is basically a collection of unexploded bombs. You're right that graceful error handling can be functionally identical to null-checking if statements. But what happens when something you convinced yourself couldn't ...


69

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


62

null is evil There is a presentation on InfoQ on this topic: Null References: The Billion Dollar Mistake by Tony Hoare Option type The alternative from functional programming is using an Option type, that can contain SOME value or NONE. A good article The “Option” Pattern that discuss the Option type and provide an implementation of it for Java. I have ...


58

I do it all the time with things like conversion errors in D: import std.conv, std.stdio, std.exception; void main(string[] args) { enforce(args.length > 1, "Usage: foo.exe filename"); double[] nums; // Process a text file with one number per line into an array of doubles, // ignoring any malformed lines. foreach(line; ...


58

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


55

While Steven's answer provides a good explanation, there is another point which I find is rather important. Sometimes when you check an error code, you cannot handle the failure case immediately. You have to propagate the error explicitly through the call stack. When you refactor a big function, you may have to add all the error-checking boilerplate code to ...


55

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


54

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


53

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


48

Returning exceptions instead of throwing them can make semantical sense when you have a helper-method for analyzing the situation and returning an appropriate exception which is then thrown by the caller (you could call this an "exception factory"). Throwing an exception in this error analyzer function would mean that something went wrong during the analysis ...


47

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


45

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


43

Is it OOP related only? No. Exceptions and OOP are unrelated. Exceptions handling is a mechanism to handle errors. An exception is handled by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler. Comparing C (not really OOP language, possible to somehow emulate ...


42

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


41

The example you cite is due to poor API design (there is no clean way to check whether a String is a valid integer except trying to parse it and catching the exception). At the technical level, throw and try/catch are control flow constructs that allow you to jump up the call stack, nothing more and nothing less. Jumping the up the call stack implicitly ...


39

I'll direct my answer more to what comes after an exception: what's it good for and how should software behave, what should your users do with the exception? A great technique I came across early in my career was to always report problems and errors in 3 parts: context, problem & solution. Using this dicipline changes error handling enormously and ...


39

In my opinion you should put everything in the block that is dependent on the part that throws the exception. So if in your second example: try { thisThrowsAnException(); thisDoesnt(); } catch (Exception e) { e.printStackTrace(); } If thisDoesnt(); is dependent of a successful execution of thisThrowsAnException() it should be included. Does it make ...


39

As some additional commentary on @Nemanja's answer (which, since it quotes Stroustrup, is really about as good of an answer as you can get): It's really just a matter of understanding the philosophy and idioms of C++. Take your example of an operation that opens a database connection on a persistent class and has to make sure that it closes that connection ...


38

One example where I think is OK to just swallow exception without doing anything, even logging the exception, is inside logging code itself. If you tried to log something and got exception there is not much you can do about it: you can not log it of course; you might be able to fall back to a reserve logging mechanism, but most applications are not that ...


38

Exception specs are bad because they're weakly enforced, and therefore don't actually accomplish much, and they're also bad because they force the run-time to check for unexpected exceptions so that they can terminate(), instead of invoking UB, this can waste a significant amount of performance. So in summary, exception specs aren't enforced strongly enough ...


38

When should an exception be thrown? On the high level for some people the answer is clear and for some it is more a philosophical question. For many it is something in between and a question of judgment. However when it comes to code, I think that following explanation for the term exception is very helpful: An exception is when a member fails to complete ...


36

From Why doesn't C++ provide a "finally" construct? in Bjarne Stroustrup's C++ Style and Technique FAQ: Because C++ supports an alternative that is almost always better: The "resource acquisition is initialization" technique (TC++PL3 section 14.4). The basic idea is to represent a resource by a local object, so that the local object's destructor will ...


35

Almost any console game out there is in C++ with exception deactivated, even today. In fac it's the default setup for C++ compilers targeting those consoles. Sometimes some C++ features are not guaranteed to work correctly on those compilers, like multiple inheritance (I'm thinking about a very well known console default compiler for example). Also, ...


35

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



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