Unexceptional exceptions

164 views Asked by At

Is this a thing?

I want to throw my own exceptions just to make it easier to handle. They're unexceptional though because it is likely to happen, not an exceptional case. Such as if the user selects a wrong file type from a browser. Yes I could handle it but it would be far easier if I threw an exception especially for sub methods, since I would need to somehow tell the parent method that the sub method failed so do something differently. This I think is easier with throwing exceptions.

So is it okay to throw an exception in normal situations?

2

There are 2 answers

1
Robby Cornelissen On

I would have to say answers to this question are to some extent opinion-based, but the general consensus seems to be that it's a bad idea to abuse exceptions for regular flow control.

It's a well-documented anti-pattern, and the primary reasons for it to be considered as such are that:

2
laune On

The typical use case is:

  1. Present some data to the user
  2. Accept a selection (or a cancellation)
  3. Check the selection (e.g., correct file type)
  4. If correct, return the selection
  5. If not correct, provide an error message (still in the context of this dialog) with the choices "retry" and "abort"
  6. On abort, return a "null value"
  7. On retry, go back to 2.

There is really no need for an exception to handle incorrect entries or even the cancellation (after 2 or 6). Some other exception might be thrown if your program runs into an IOException while accessing the file system or similar.

The only burden the caller should have is to check for a "null value" (null or whatever is suitable) being returned to indicate user's choice of not wanting to do something - an option that should typically be provided.