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.
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.