How can I distinguish between truly exceptional circumstances and routine poor condition?

Many developers say they only throw exceptions in truly exceptional circumstances. One of them will be if the external hard drive I want to burn is not enabled (hence not a connected / registered drive). However, there are some situations that are difficult to decide whether they are truly exceptional or not.

For example, enter a string for the folder path, but it was not found. In this case, if there is any entry that cannot be found (for example, a name in a collection that was not found), is it best to just return an error and some action?

eg.

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?

Can an exception be thrown in an else or if statement? Looking at the list of code smells related to exception handling I would be of great help.

+1


source to share


3 answers


Typically, it works like this:

If you can handle the situation without any interruption, do so. (The file does not exist, but its input is not essential to continue working [preferences, additional configuration, etc.])

If you need user intervention, ask them. (The file does not exist, but you need to keep it running)



If this is a problem that the user cannot fix (due to insufficient memory, faulty hardware, etc.) then throw an exception.

Each place has its own standard for details, but I believe the above works.

+1


source


  • if your code can recover from an exception then do this
  • if it would be acceptable to require clients to validate the return value for minor expected exceptions, do so - this is a call for a solution, see below
  • in all other cases, throw an exception (or don't catch the called method exception)

for the second case, insignificant and expected are highly context dependent

IMHO does not use exceptions for control flow, but in all other cases, you are probably more safe to throw them



Note that in some of the "optimization" guidelines, you check for conditions instead of relying on exceptions, for example. file-not-found, but in reality you should still expect an exception because the file might be deleted or moved between the statement that checks for existence and the statement that tries to open the file!

Summary: In general, throwing elimination is the safest course. Of course, a direct warning or user request should only be done in the UI code!

+1


source


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

0


source







All Articles