If or try/catch and why

Java coding question:
Preface: I should probably know this, but I don’t.

When is the appropriate time to use exceptions? For example, lets say I have an inventory list, and I press A to choose the first inventory object. However, there is no inventory object to choose yet, because I haven’t collected anything, hence I get a null pointer.

How I’ve always done it (maybe besides work when I used PHP and got code reviewed) was:
if (inventory > 0) doThis();

What is better? To do it that way, or try/catch a null pointer? And why?

Exceptions are for things that aren’t supposed to happen in an ideal world - for things you are genuinely not expecting. An empty inventory is not unexpected.

Exceptions are also expensive to construct, where that matters.

Thanks @princec. Could you give me an example of something that isn’t supposed to happen in the real world (in coding)? Not code, just an example in plain english? (But American English not your England bollocks :).

I guess I’m confused as to when and why I would want to use an exception opposed to why not just check if the thing IS NOT null.

Why, in my pirate game, would I use a try catch?

Let’s say in your pirate game you need to transfer loot from one player (A) to another (B), over the network.

Let’s say you use HTTP.

Let’s say that you call your server to start the transfer.

The HTTP request library returns back a response object, with a status code, and a response body.

However, maybe player A’s network connection fails before the request completes. The library can do a few things. It can return a response object indicating what happened, or it can throw an exception.

In this case the library just returns a status code and response body, and since an invalid network connection does not fit within the bounds of that interface, all it can do is either silently fail or throw an exception since this is an exceptional condition. You don’t normally expect this to happen, it’s an exception.

Exceptions are used whenever you want to handle control flow that is out of bounds of the consumed interface. For example we get by without exceptions in C, because everything has to return an error code (or maybe a pointer to where one gets populated). But then you have to check “if this didn’t fail” everywhere. But then we’re just getting into personal preferences.

3 Likes

Ok thanks, this all makes a lot more sense now.

The definitions I’m finding are pretty broad, e.g., the following from the Java Tutorials.

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

It seems to me that there’s a lot of “grey area” in defining what is normal or not.

I found the following in a tut called 7 Common Mistakes You Should Avoid When Handling Java Exceptions.

Mistake 4: Use exceptions to control the flow

Using exceptions to control the flow of your application is considered an anti-pattern for two main reasons:

  1. They basically work like a Go To statement because they cancel the execution of a code block and jump to the first catch block that handles the exception. That makes the code very hard to read.
  2. They are not as efficient as Java’s common control structures. As their name indicates, you should only use them for exceptional events, and the JVM doesn’t optimize them in the same way as the other code.

I can’t find anything that goes to any depth as to how much less efficient this form of branching is. I think it’s reasonable to accept the statement that a normal branch is preferred at face value.

I have a couple suggestions to consider on the inventory array example given. For one, I’d change things up so that you always have at least an empty array rather than a null. In that case, you’d be checking for an array out of bound exception, and the null condition (for the array itself) should never arise.

I’d also reconsider if the GUI option for “get first inventory item” should even be enabled if the inventory array is empty.

1 Like

Thanks @philfrei! That makes even more sense, I didn’t realize try catches worked like that. And that’s a good idea for the inventory example, I’ll see if it’s not too much hassle to change the code, as it’s become somewhat spaghetti like now that I’m almost done lol.

Super inefficient. Not only is the control flow not optimised in any way, but to construct an exception is really expensive.

1 Like
  • Exceptions force API users to apply defensive programming
  • Exceptions allow you to immediately escape multiple nested code blocks. To achieve that with return values, you have to use goto statements, which is a common pattern in C to do exactly that.
  • An exception can traverse multiple stack frames in the call stack until it reaches the appropriate place to be handled. This is something you have to write explicitly, when using return values.
  • Dynamically instantiated exceptions are expensive in terms of memory management effort (including garbage collection). But you can as well throw globally defined constant exceptions (aka singleton), if that makes sense in the particular case.
1 Like