New answers tagged

2

I normally perform these sorts of checks at the boundaries to sets of components e.g. for third party consumers. If you assert the incoming arguments for null-ness (and anything else) then your clients will get a clear message as to how they're misusing your API, and from that point on you can be reasonably safe in assuming that your input data is in a good ...


5

I prefer NOT littering my code with null checks, because it's basically just clutter. Yes, sometimes it's necessary, like when reading user input or operating at application boundaries, getting stuff from third-party services etc. But keep your business logic clean. If a parameter can't be null, trust that it isn't null. In fact, you should try to avoid or ...


0

IMHO if it is for a library, I think it is ok to throw an exception so that the consumer of the library will know that there something need to change on the implementation of the method. But if it is used for "final production" that will interact to the user, I think showing a message telling them that there is something wrong happen, then after that the ...


1

If you're going to serialize a class, it needs a serialVersionID. Your exception classes should always be serializable. You have no idea where the exception might be used, and if it gets marshaled across an app domain, you may lose debugging information or even lose the entire exception altogether. Exceptions are intended to be usable anywhere, and if ...


2

Something about writing code this way makes me feel like an abuser. I do not understand, why you feel this way. This is how life is (in a distributed system): You have one job and you try to do your best to do it. When the counterpart fails for whatever reason, it's not your fault. What you should do is doing your job in a sane way, meaning define ...


1

No. Others have noted that you may perhaps want to show users all exceptions in a nice dialog, or save them to a log. These are not terribly bad ideas. But what happens when the exception is a StackOverflowException? An OutOfMemoryException? You may even get a ClrException! In essence, you simply can't catch them all. You can try, and it may even provide ...


8

Yes. Anytime exceptions could be exposed to end users or external systems, it might be a good idea to catch all possible exceptions, perform some generic handling (like logging) and emit a generic message. Both for usability reasons and for security reasons (an exception might contain sensitive information). But often this top-level exception handler would ...


1

Yes. At the very least, it's justifiable on the client side for applications that serve non-technical users, provided you're giving the user meaningful instructions. For example, "There was an internal error. Please reload the page." Exceptions should always and only be caught at the point that something meaningful can be done to correct the problem.


0

As others said, retrying after a (rare) exception is fine. But I would spend some time testing whether a failed upload guarantees an exception; if not you need some way to verify which uploads worked.


1

Catching Exception is usually the wrong thing to do, however there are cases where it is acceptable and the right thing to do. When writing web APIs, you might not want to reveal too much information about exceptions to your clients. You may also have designed into your API an error indicator so that clients can use this to decide what to do next. In this ...


2

Pokemon exceptions ... Ever acceptable? Never say (N)ever, but here goes. A concise conceptualization of exceptions shows why. A try block tells me what situations I choose to not handle Where to try, catch, and after-the-fact handle exceptions is a design issue. Focused try blocks convey the program's concerns. Unreliable connections, undefined ...


0

Nulls are problematic because they must be explicitly checked for, yet the compiler is unable to warn you that you forgot to check for them. Only time-consuming static analysis can tell you that. Fortunately, there are several good alternatives. Take the variable out of scope. Way too often, null is used as a place holder when a programmer declares a ...


4

Using exceptions for flow control is highly frowned upon in most languages, but not in Python. Using exceptions for flow control in Python is "pythonic." Exceptions are at the heart of how python for loops work, which terminate the iteration on receiving a StopIteration exception. Python has a slightly derogatory term for languages such as C++, Java, and C# ...


0

I think you're fundamentally misunderstanding how arguments to function work. First, let me point you the correct way to raise an error if someone enters the wrong type: def SCounter (x): assert isinstance(x, int), "Value is not of type int!" // carry out your code normally Here: The 'assert' keyword can be thought of as a short version of a ...


0

First of all, as long as you don't know that the piece of code in question actually is a performance bottleneck, don't bother optimizing it and write it in the most clear, straightforward way that you can think of. Whether the exception is faster than the explicit check depends entirely on the language/compiler. To be more precise, there are two points ...


2

Python has a builtin method setdefault which does exactly what you need: self.layers.setdefault("pos", []).extend(node)


0

I hear this misguided idea a lot: "exceptions are situations in your code that you should never reach. By their name, they suggest exceptional, unexpected and uncontrollable situations. Throwing an exception should stop the execution of your code all together." This is misguided because, suppose you want to access a file, and the file cannot be accessed ...


-1

Yes this is a bad coding practice, since it obfuscates what is going on. Worse, since throwing an exception is such an expensive operation in pretty much every language, this won't even get you anything performance-wise! (Though I would measure to make sure)


6

Both of those are "functional-style" error handling. The only difference is the latter lets you specify that it will handle certain exceptions functional-style while leaving the rest to be handled imperative-style, while the former handles all exceptions functional-style, forcing the programmer to rethrow any unhandled exceptions manually. The main ...


3

There is a simple general strategy that helps you make this decision. Consider how the exception would be handled if it was to be thrown. So imagine your music player, user clicks stop and then stop again. Would you want to display an error message in that scenario? I haven't yet seen a player that does. Do you want the application behaviour to be any ...


2

Here is how android does it: MediaPlayer In a nutshell, stop when start has not been called is not a problem, the system stays in stopped state, but if called on a player that does not even know what it is playing, an exception is thrown, because there is no good reason for calling stop there.


1

What should be the general rule when a method is not supposed to be called in some situation, but it's execution does no harm to the program in general? I see what could be a minor contradiction in your statement that may make the answer clear to you. Why is it that the method is not supposed to be called and yet it's execution does no harm? Why is ...


11

The purpose of exceptions isn't to signal that something bad has happened; it's to signal that Something bad has happened that I don't know how to fix here that the caller, or something up the callstack from it should know how to deal with so I'm bailing out quickly, halting execution of the current code path in order to prevent damage or data corruption, ...


3

The rule is you do what the contract of your method requires. I can see multiple way to define meaningful contracts for such a stop method. It could be perfectly valid for the stop method to do absolutely nothing if the player isn't playing. In that case, you define your API by its goals. You want to transition to the stopped state, and the stop method does ...


0

I prefer designing the API in a way that makes it harder or impossible for the consumer to make mistakes. For example, instead of having MediaPlayer.play() and MediaPlayer.stop(), you could provide MediaPlayer.playToggle() which toggles between "stopped" and "playing". This way, the method is always safe to call - there's no risk of going into an illegal ...


17

There are two distinct kinds of actions one may wish to perform: Simultaneously test that something is in one state, and change it to another. Set something to a particular state, without regard for the previous state. Some contexts require one action, and some require the other. If a media player which reaches the end of content will remain in a ...


5

Look at it this way: If the client calls Stop() when the player isn't playing, then Stop() is automatically successful because the player is currently in the stopped state.


11

There is no general rule. In this specific case, the intention of the user of your API is to stop the player from playing the media. If the player is not playing the media, the MediaPlayer.stop() may do nothing and the goal of the method caller will still be achieved - the media is not playing. Throwing an exception would require the user of the API to ...


35

There is no rule. It's entirely up to how you want to make your API "feel." Personally, in a music player, I think a transition from the state Stopped to Stopped by means of the method Stop() is a perfectly valid state transition. It's not very meaningful, but it is valid. With this in mind, throwing an exception would seem pedantic and unfair. It would ...


1

What exactly do MediaPlayer.play() and MediaPlayer.stop() do?-- are they event listeners for user input or are they actually methods which start some sort of media stream on the system? If all they are are listeners for user input, then it's perfectly reasonable for them to do nothing (although it would be a good idea to at least log them somewhere). ...


6

The predefined exception does not work as you describe. When a predefined exception is thrown, it is just because there is a throw-statement somewhere indside the framework library, which is called as part of the regular execution path. If I understand you suggestion correctly, you propose that a exception class should be able to detect automatically when a ...


2

I maintain a large collection of classes who interface and wrap around a range of hardware from bill acceptors and printers to custom circuit boards utilizing multiple communication interfaces. I think that you should pick the exception that best describes what caused an issue. For example, if the parities of the bytes didn't match up then throw a ...


1

There is no simple answer. Put yourself in the role of the user and think what they would expect, if there is a data file that is corrupted in the middle. Let's say I have an address book with 1200 addresses, and there is one that your code cannot read. As a user, I expect to see 1199 addresses. Do I even expect an error message? I don't think so. Or at ...


2

Don't you want to abstract out this functionality ? e.g. you may want to log to a file, to a network socket, to stdout etc. I certainly don't think that your classes should know about files etc. but about an abstract logger, and you can decide later how this is going to work. This is a very common requirement, and you'll find libraries already exist to do ...


1

You could turn things inside out like this: function getValue(parameter) { if (active) { try { return valueStore.query(parameter) } catch (e) { // quietly fall back to non-active behavior } } return getRandomValue(); } Now there's no duplication or local exceptions. Should the fall back logic ...


1

Validation is making sure that something is in the state you expect it to be. For example, the User enters "a Date". Of course, users can't actually enter "a Date"; they can only enter the character representation of "a Date", in a format "defined" defined by their national/geographical location and/or personal preference (yes; Users can change their ...


1

Sure, you can have a parser to parse the message of an exception, pass this message to the ExceptionHandler class and do some logic on it. But even better would be to rethink your design. You are most likely forced to handle the message because your exception tree is incorrectly designed. You want the exception classes to represent the exceptional states, ...


1

So far, I think you are doing well. Look it from this point of view. Unchecked Exceptions - Controversy. If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception. May be is a inherited handicap. Spring Rest Client ...



Top 50 recent answers are included