0

Hello I am trying to get a clearer understanding of when to use exceptions and when to not use them. I will give a few case scenarios. Can you let me know which cases I should use exception, and explain why I should or should not? (note: this is not a homework problem).

Scenario 1: I design a computer game where each unit can move to a square on a board. However, some square can be blocked. Should I throw a SquareIsBlockedException to prevent the movement of the unit?

Scenario 2: I insert a record to the database, however it fails because there the unique ID is already present. It throws a DuplicateIDException.

Why should I use exceptions for scenario 2, but not for scenario 1?

Anon21
  • 2,545
  • 6
  • 31
  • 43

2 Answers2

1

1) No. A square being blocked is not an exceptional thing - one can assume it is quite common in your game. Exceptions should be fired when something happens in your program that shouldn't happen.

2) Possibly. Inserting a duplicate record into the database is something that should not happen normally. It might also hint at a bug.

If you fire the exception, you stop the execution flow. This is good - after your system finds out it's inserting a duplicate row, what should it do? It's very likely that you haven't prepared your system to behave correctly in such a scenario. Plus, you can (in your debugger, in your logs, etc.) see what went wrong, which makes fixing your code easier.

Filip
  • 2,108
  • 1
  • 16
  • 24
0

It all depends on the use case and in your two examples it could be meaningfull to use exceptions or not.

Exceptions should be used for ... Exceptions. There are some "bad code" examples in the web where Exceptions are used for flow control. Do not do this.

So Ex1 sounds for me for a flow control, use if's or language flow control.

In Ex2 explicit control of duplicates can lead to more code when it is necessary first to hit the db to look up if the ID is already in. Is the ID an automatic id, use Exceptions because the normal case is that autom. ID are all diferent. Is the id a user editable data field (e.g. name), lookup first if the Id already exists.

PeterMmm
  • 22,286
  • 12
  • 68
  • 104