Tag Info

New answers tagged

6

Continuing under parse errors can be a bit nontrivial, and simply crying “parser combinator” will not fix that. The central point is that your parser won't throw exceptions when it encounters syntax errors. Instead, these exceptions are queued in a list until a problem is sufficiently fatal, you have too many problems, or the end of input has been reached. ...


1

Creating a class is easy. It's not a time consuming process at all. Debugging code which hides the problems is hard. And time consuming. When deciding to create an exception or not the question you should be asking yourself is "is this behaviour normal, expected behaviour, or is this behaviour exceptional". In this case, the expected behaviour is that ...


4

Use a custom exception when you want users to be able to programmatically distinguish between certain error conditions. If that situation does not exist, you can throw a more "general" exception, and avoid creating the custom exception class. In the specific case of your SetOperatingMode() example, unless you need to call out specific ways that this method ...


3

I usually do the following unless there is a good reason not to. The member check acts as a "Guardian Clause" and the need for temp variables disappears if you are returning a constant in the case of an exception. private String getMyString() { if (!mStrigMember.isEmpty()) return mStrigMember; try { return ...


1

On the conventional wisdom that states that you should only throw an exception when a condition occurs that you can't handle in your code we tend to focus on the definition of an exceptional condition but ignore the definition of what it means to handle the exception. A process may encounter a exception communicating with a particular node and may handle the ...


3

You seem to have some misunderstandings about exceptions, so let's try and clear those up first. Throw an exception when some condition occurs that you can't handle in your code. For example, if your code is supposed to open a file and do something with that file, but the user supplies a path to a file that does not exist, then you should throw an ...


3

In my opinion, yes. All logic - meaning all conditional code - can be tested. And this is an edge case, too. By the way, this code is not thread-safe - _totalCount could change between reading its value in if and actually dividing by it. But thread-safety might not be among your requirements. As for the check being explicit or not, it's a matter of ...


6

Is just checking that a property doesn't throw an exception a "valid" test? Yes, it can be. In this example, I would explicitly check that FailRate returns 0 for that input. And I certainly would validate that the bad input is handled properly by writing the test. I'd probably write a test with a negative value as well to make sure it was > 0 rather ...


3

You are handling errors across the boundary between two systems, effectively, so its best to think of the http handler as a system and the internal logic that throws these internal exceptions as a library. Given you want to catch these at the boundary point, and you do not want to map internal to external exceptions, then you're left with a simple catch-all ...


0

You can create reusable utility class that will resolve correct HttpException. try { securityService.login(credentials); } catch (InternalException e) { throw ExceptionUtil.resolveHttpException(e); } public class ExceptionUtil { public static HttpException resolveHttpException(InternalException exc) { if (exc instanceOf ...


0

My belief is that you can just send the response from the error handler or test the data before sending if possible. Can also use a preload step during app initialization from your REST interface and store valid value parameters and use those on your client to test data going out. It would be simple to try to send a response from your handler. Garbage ...


2

Optional is the correct solution. However, if you prefer, there is an alternative which has less of a "two nulls" feel, consider a sentinel. Define a private static string keyNotFoundSentinel, with a value new String("").* Now the private method can return keyNotFoundSentinel rather than throw new KeyNotFoundException(). The public method can check for ...


3

I know I am late to the party, but anyways your use case resembles how Java's Properties lets one define a set of default properties too, which will be checked if there is no corresponding key loaded by the instance. Looking at how the implementation is done for Properties.getProperty(String) (from Java 7): Object oval = super.get(key); String sval = (oval ...


2

There are some great answers here, but I think one important reason has not been emphasized enough: When exceptions occur, objects can be left in invalid states. If you can "catch" an exception, then your exception handler code will be able to access and work with those invalid objects. That is going to go horribly wrongly unless the code for those objects ...


2

Learn from the framework that learned from all Java's pain points: .NET provides two far more elegant solutions to this problem, exemplified by: Dictionary<TKey, TValue>.TryGetValue(TKey, out TValue) Nullable<T>.GetValueOrDefault(T default) The latter is very easy to write in Java, the former just requires a "strong reference" helper class. ...


3

Though I think @BЈовић's answer is fine in case getValueByKey is needed nowhere else, I don't think your solution is bad in case your program contains both use cases: retrieval by key with automatic creation in case the key does not exist beforehand, and retrieval without that automatism, without changing anything in the database, repository, or key map ...


5

There's this Preferences class, which is a bucket for key-value pairs. Null values are legal (that's important). We expect that certain values may not be saved yet, and we want to handle these cases automatically by initializing them with predefined default value when requested. The problem is exactly this. But you already posted the solution yourself: ...


7

Since there's no performance considerations and it's an implementation detail, it ultimately doesn't matter which solution you choose. But I have to agree it's bad style; the key being absent is something that you know will happen, and you don't even handle it more than one call up the stack, which is where exceptions are most useful. The tuple approach is ...


11

I wouldn't call this use of Exceptions an anti-pattern, just not the best solution to the problem of communicating a complex result. The best solution (assuming you're still on Java 7) would be to use Guava's Optional; I disagree that it's use in this case would be hackish. It seems to me, based on Guava's extended explanation of Optional, that this is a ...


68

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


0

So here, you're writing the handler that throws the exception and the grid manages that exception itself. I see this as fair enough - after all, you're writing the library code that throws on error states, and the caller (ie the grid) catches and manages the exception how it likes, in this case showing a message to the user in a dialog (which is perfectly ...


2

Since the .NET framework standard UI controls do not catch unhandled exceptions by themselves, and offer you some mechanisms to catch those exceptions in a central place, I agree that it is questionable why a 3rd party control should behave differently. Lets assume, from the nature of your application, in case of a severe failure, you are 100% sure you can ...


1

I am very fond of hard error & fail fast, I believe they are the one true and right way to go, but I try not to be dogmatic about them. There are cases where the best thing to do with an unexpected exception is to log it and swallow it. I will give you an example which is more simple than your situation: suppose you have an observable collection which, ...


1

I recently solved a similar problem with a third-party library. Allow me to restate to make sure I'm not misinterpreting your situation. You know how to work around it, but you don't like the repetition of the workaround, and you feel it obscures your actual code? I solved my problem using a python decorator that catches an exception and handles it ...


2

What is there to do. In my view, the decision to turn an exception during validation into a failed validation is a correct way of handling such exceptions. Letting the exception pass through and crash the application has a significant risk that you lose the work the user had been doing, even if the situation was caused by bad user-input and entirely ...



Top 50 recent answers are included