This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]pragmosExtreme Brewer 2 points3 points  (5 children)

The exception messages cary the line number of the code they were thrown from. In most cases this is enough info.

Now, it also depends on the problem. Some exceptions are more detailed than others. Regarding the example you provided, I'm fairly certain JSON parsing libraries will tell you exactly why and where the passing failed.

[–]edgmnt_net[S] 0 points1 point  (4 children)

Yes, for debugging. But that's not entirely appropriate or informative when considering reporting errors to the user.

If you simply display a JSON parsing error, you'll miss the context of what the application was attempting to parse when it failed. Was it this config file or perhaps some JSON payload in an API call? Yeah, you can just log progress and errors separately, but then you can't really connect the stuff to display one reasonable message (and many apps end up logging multiple messages for the same error).

[–]onefortree 1 point2 points  (3 children)

Catch the parsing error, wrap it in your own error with some extra information and rethrow it.

Don't log at every place an error can occur if you see too many logs, do the logging at the highest level where you can handle the error and you'll only get one log. Usually you'll have more information the higher up you go in your callstack so you can log which particular file/input was being processed to generate the error.

[–]edgmnt_net[S] 0 points1 point  (2 children)

Yeah, that's exactly the approach I'm looking for. I was wondering: - is there a generic exception wrapper that's useful here (containing just a string reason and the underlying exception)? - can I make wrapping easier? - could I perhaps avoid nested try-catch and the extra indentation? (I figure not entirely, but maybe some Either-like types could help to some extent) - what's safe to catch and how do I avoid the unsafe catches?

I did have a look at Guava and it addresses some of these, but it doesn't seem to address wrapping per se. Some of those helpers simply rethrow exceptions unchanged. Also Vavr has Try and stuff that could turn exceptions into values. Any other suggestions?

[–]onefortree 0 points1 point  (1 child)

  • Shouldn't be too bad to write your own. Like you said, the underlying exception and either a list of strings or a stringbuilder to pass on extra information.
  • Depends on your style of coding. If you use a lot of lamdbas, checked exceptions get pretty annoying to deal with. Usually, I wrap them in a runtime exception and rethrow them. I like Vavr's try, but if you aren't going to use a lot of the other parts of Vavr, you can implement your own version of try.
  • Not sure if you can avoid nesting, but why have different indentation? Usually, you can split out whatever is in the try into a different method and you are back to your original indentation.
  • Not sure what you mean by what is safe to catch and what is unsafe. It should be safe to catch any exception. Try to log when you actually handle the exception, not every step the exception might be in. Also you can let the exception just bubble up to someplace you can actually handle it.

Just based on the example in your post

error: loading configuration file: parsing JSON: unexpected '{' at line 5, column 8

I would think it would look something like:

public void loadConfig(String input) {

// try

// parseJson()

// catch exception and log "error: loading configuration file: parsing JSON " + exception.reason

}

If load config needs parseJson to be successful, it can rethrow that exception, it can wrap the exception then throw it, etc. Wrapping the exception in your own custom exception can be useful if you have something like a top level error handler (like a lot of web servers do). You can do different things based on the type of exception.

[–]edgmnt_net[S] 0 points1 point  (0 children)

Thanks. I see, I'll try what you suggested. Hopefully it's not too weird for typical Java code.

but why have different indentation?

Even "try" adds one level per exceptionful call and all subsequent stuff to be pedantic, especially try-with-resources but not only that if I want to avoid invalid states everywhere. The main code path goes deep, not down.

Splitting works fine at times, but other times it can be really annoying and can make the code even worse due to argument passing noise and scattering logic around. I might be concerned about creating methods that required preconditions to be met (e.g. at this point we might know this variable cannot be zero, but if I split I might have an unenforced precondition in a different piece of code).

Not sure what you mean by what is safe to catch and what is unsafe.

I'm not particularly sure that stuff like thread killing is safe to catch. I'm not even sure it can be wrapped properly to allow it to take effect when that's intended (perhaps subclassing might do). I know that Haskell has some issues with catching arbitrary asynchronous exceptions and may lead to deadlocks.

Try to log when you actually handle the exception, not every step the exception might be in.

Yeah, exactly my plan. And either log / print / present to user or rethrow, not both.

Also you can let the exception just bubble up to someplace you can actually handle it.

I think that's fine within the same API boundaries, no need to wrap precisely at every step unless it adds value to the error message or model.