tags:

views:

51

answers:

3

A lot of developers say only throw exceptions in truly exceptional circumstances. One of these would be if an external hard drive I want to write to is not switched on (therefore not a connected/registered drive). However, there are some situations which are difficult to work out whether they are truly exceptional or not.

For example, entering a string for a folder path but it is not found. In this case, if there is any input which cannot be found (like a name in a collection which is not found), is it best to just return an error message and some action?

E.G.

public void Find(string name) { if(Names.contains(name) { string s = Names.get(name); }

if(!Names.contains(string name) { throw new ???Exception;

Or Do something like display a popup and handle the situation gracefully? } }

Is it wise to throw an exception in an else or if statement? Looking at a list of code smells regarding exception handling would do me a lot of favours

Thanks for the help (in advance)

+1  A: 

Generally, it works like this:

If you can handle the situation without any interruptions, do so. (File doesn't exist, but its input isn't essential to continuing operation [preferences, optional configuration, etc])

If you need user intervention, ask them. (File doesn't exist, but you need it to continue operating)

If it's a problem the user can't fix (out-of-memory, failed hardware, etc), then throw an exception.

Each place has their own standard for the details, but I find the above to work generally.

xtophyr
+1  A: 
  1. if your code can recover from the exception, do so
  2. if it would be acceptable to require clients to check a return value for minor expected exceptions, do so - this is a judgement call, see below
  3. in all other cases, throw an exception (or don't catch a called method's exception)

for the second case, minor and expected are highly context-sensitive

IMHO don't use exceptions for control-flow, but in all other cases you are probably safer throwing them

note that some 'optimization' advice tells you to check for conditions instead of relying on exceptions, e.g. file-not-found, but in reality you should still expect the exception because a file may be deleted or moved in between the statement that checks for existence and the statement that tries to open the file!

summary: in general, throwing exceptions is the safest course. Of course, directly warning or asking the user should only be done in the user-interface code!

Steven A. Lowe
A: 

Exceptions should be used if there is something that can be done about it, but the code that detects it can't known what to do.

BCS