Tag Info

Hot answers tagged

89

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


79

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


60

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


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


54

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


52

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


52

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


52

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


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


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


41

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


40

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


40

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


38

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


38

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


36

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


36

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


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


34

Purely from a style standpoint, I think these three lines: T current = next; next = fetcher.getNext(); return current; ... are both more obvious and shorter than a try/finally block. Since you're not expecting any exceptions to be thrown, using a try block is just going to confuse people.


34

to hide what the core cause was in places where it doesn't matter the top level only needs to know that a storage exception occurred instead of an SQLException, which may not happen if you decide to migrate to a non-sql data store not wrapping also leaks the abstraction and requires reimplementation of the top level when doing a migration of a lower level ...


33

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


33

Yes, it's fine (actually, it's good) to make the default constructor unusable if there's no sensible way to initialize the object without any arguments. But don't "disable" it by throwing an exception. Make it private instead. Ideally your interface won't contain any methods or constructors people "aren't supposed to" call.


31

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


29

There are several problems with using null references in code. First, it's generally used to indicate a special state. Rather than defining a new class or constant for each state as specializations are normally done, using a null reference is using a lossy, massively generalized type/value. Second, debugging code becomes more difficult when a null ...


29

Assertions should only be used to verify conditions that should be logically impossible to be false (read: sanity checks). These conditions should only be based on inputs generated by your own code. Any checks based on external inputs should use exceptions. A simple rule that I tend to follow is verifying private functions' arguments with asserts, and using ...


29

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


27

To explain exception handling, explain the concept behind it: The code where an error occurs frequently does not know how to properly handle that error. The code that knows how to handle it properly could be the function that called that one, or it could be further up the call stack. When you write a routine that calls a routine that might throw an ...


27

I'm concerned about this because I am developping a project which involves a heavy use of recursive structures and recursive function calls. I don't want the application to fail when I start using it for more than just small tests. Unless your language environment supports tail call optimization (and your recursion is a tail call), a basic rule of thumb ...


27

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


26

Usual way of error handling is this : if you can solve the problem locally, then use if statement (or if the function throw an exception, handle that exception) if you can not solve the problem locally, then throw an exception (or if the function throw an exception, let it propagate further), and handle it where you know what to do about it



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