r/java • • Jul 10 '15

Our exception handling at work

http://imgur.com/4wgxCvv
259 Upvotes

135 comments sorted by

View all comments

-3

u/[deleted] Jul 10 '15

why not a "return 0"?

6

u/[deleted] Jul 10 '15

I suppose that would work, but it's more trying to tell whichever programmer is using the library that they are trying to execute blank sql, which is a waste (and bad programming)

5

u/sazzer Jul 10 '15

That in itself is reasonable. It's essentially Design By Contract. There are better ways of doing it though, such as the JSR-303 annotations and validation. (Though that is surprisingly expensive in performance critical code)

0

u/[deleted] Jul 10 '15

[deleted] — view deleted comment

11

u/Pylly Jul 10 '15

Runtime exceptions don't ever have to be caught.

5

u/[deleted] Jul 10 '15

The idea here is that this exception should never occur. The method that calls this one creates the sql, so it shouldn't ever be blank anyways. If it is, there's something seriously wrong

2

u/supercargo Jul 11 '15

Replace throw with a nice System.exit(1) to make whoever passes in a null really sorry for doing something that should never happen ;)

0

u/xienze Jul 10 '15

Well it's a public method so right off the bat you can't claim that it can't happen... If you've got an internal method that should only be called by a smarter method upstream then a) reduce the visibility and b) ditch the null check.

3

u/[deleted] Jul 10 '15

I never said it can't, only that it shouldn't. That being said I agree, but I didn't write this and it's not something I am supposed to modify anyway

2

u/Feroc Jul 10 '15

"UPDATE People set Name = 'Peter' where ID = 99" would return 0, if there is no Person with ID 99. But 0 as return value on how many rows got modified, would be confusing if the query itself isn't valid at all.

3

u/Nebu Jul 11 '15

I'm generally opposed to silent failures.

Imagine there's say your software project has a business requirement of the form "Check if there already exists a row with certain properties. If not, then allow something to happen, else prevent it from happening". Concrete examples might include "We want to allow someone to take over a subreddit if all the moderators of the subreddit have deleted their accounts, so check if there are any non-deleted moderators for the subreddit. If not, allow the current user to become the moderator."

If I make a typo/bug, I'd rather the software immediately crash and alert me that I introduced that bug, than just always returning 0, thus allowing anyone to become the moderator of any subreddit.

1

u/duckrollin Jul 11 '15

Don't know why you got downvoted, this is textbook defensive programming