Example of “using exceptions to control flow” [closed]

夙愿已清 提交于 2019-12-17 14:04:09

问题


What would a piece of code which "uses exceptions to control flow" look like? I've tried to find a direct C# example, but cannot. Why is it bad?

Thanks


回答1:


Bad

The below code catches an exception that could easily be avoided altogether. This makes the code more difficult to follow and typically incurs a performance cost as well.

int input1 = GetInput1();
int input2 = GetInput2();

try
{
    int result = input1 / input2;
    Output("{0} / {1} = {2}", input1, input2, result);
}
catch (OverflowException)
{
    Output("There was an overflow exception. Make sure input2 is not zero.");
}

Better

This code checks for a condition that would throw an exception, and corrects the situation before the error occurs. This way there is no exception at all. The code is more readable, and the performance is very likely to be better.

int input1 = GetInput1();
int input2 = GetInput2();

while (input2 == 0)
{
    Output("input2 must not be zero. Enter a new value.");
    input2 = GetInput2();
}

int result = input1 / input2;
Output("{0} / {1} = {2}", input1, input2, result);



回答2:


By definition, an exception is an occurrence which happens outside the normal flow of your software. A quick example off the top of my head is using a FileNotFoundException to see if a file exists or not.

try
{
    File.Open(@"c:\some nonexistent file.not here");
}
catch(FileNotFoundException)
{
    // do whatever logic is needed to create the file.
    ...
}
// proceed with the rest of your program.

In this case, you haven't used the File.Exists() method which achieves the same result but without the overhead of the exception.

Aside from the bad usage, there is overhead associated with an exception, populating the properties, creating the stack trace, etc.




回答3:


It's roughly equivalent to a goto, except worse in terms of the word Exception, and with more overhead. You're telling the code to jump to the catch block:

bool worked;
try
{
    foreach (Item someItem in SomeItems)
    {
        if (someItem.SomeTestFailed()) throw new TestFailedException();
    }
    worked = true;
}
catch(TestFailedException testFailedEx)
{
    worked = false;
}
if (worked) // ... logic continues

As you can see, it's running some (made-up) tests; if they fail, an exception is thrown, and worked will be set to false.

Much easier to just update the bool worked directly, of course!

Hope that helps!




回答4:


Here's a common one:

public bool TryParseEnum<T>(string value, out T result)
{
    result = default(T);

    try
    {
        result = (T)Enum.Parse(typeof(T), value, true);
        return true;
    }
    catch
    {
        return false;
    }
}



回答5:


Probably the grossest violation I've ever seen:

// I haz an array...
public int ArrayCount(object[] array)
{
    int count = 0;
    try
    {
        while (true)
        {
            var temp = array[count];
            count++;
        }
    }
    catch (IndexOutOfRangeException)
    {
        return count;
    }
}



回答6:


I'm currently working with a 3rd party program that does this. They have a "cursor" interface (basically an IEnumerable alternative), where the only way to tell the program you're finished is to raise an exception. The code basically looks like:

// Just showing the relevant section
bool finished = false;

public bool IsFinished()
{
    return finished;
}

// Using something like:
// int index = 0;
// int count = 42;

public void NextRecord()
{
    if (finished)
        return;

    if (index >= count)
        throw new APIProgramSpecificException("End of cursor", WEIRD_CONSTANT);
    else
        ++index;
}

// Other methods to retrieve the current value

Needless to say, I hate the API - but its a good example of exceptions for flow control (and an insane way of working).




回答7:


I'm not fond of C# but you can see some similarities between try-catch-finally statements and normal control flow statements if-then-else.

Think about that whenever you throw an exception you force your control to be passed to the catch clause. So if you have

if (doSomething() == BAD) 
{
  //recover or whatever
}

You can easily think of it in terms of try-catch:

try
{
  doSomething();
}
catch (Exception e)
{
  //recover or do whatever
}

The powerful thing about exception is that you don't have to be in the same body to alter the flow of the program, you can throw an exception whenever you want with the guarantee that control flow will suddently diverge and reach the catch clause. This is powerful but dangerous at the same time since you could have done actions that need some backup at the end, that's why the finally statement exists.

In addition you can model also a while statement without effectively using the condition of it:

while (!finished)
{
  //do whatever
}

can become

try
{
  while (true)
  {
     doSomethingThatEventuallyWillThrowAnException();
  }
}
catch (Exception e)
{
  //loop finished
}



回答8:


A module developed by a partner caused our application to take a very long time to load. On closer examination, the module was looking for a config file at app startup. This by itself was not too objectionable, but the way in which it was doing it was outrageously bad:

For every file in the app directory, it opened the file and tried to parse it as XML. If a file threw an exception (because it wasn't XML), it caught the exception, squelched it, and tried the next file!

When the partner tested this module, they only had 3 files in the app directory. The bonehead config file search didn't have a noticeable effect on the test app startup. When we added it to our application, there were 100's of files in the app directory, and the app froze for nearly a minute at startup.

To add salt to the wound, the name of the config file the module was searching for was predetermined and constant. There was no need for a file search of any kind.

Genius has its limits. Stupidity is unbounded.




回答9:


One example would be using exceptions to return a result from a recursive method:

public void Search(Node node, object data)
{
    if(node.Data.Equals(data))
    {
        throw new ResultException(node);
    }
    else
    {
        Search(node.LeftChild, data);
        Search(node.RightChild, data);
    }    
}

Doing something like this is a problem for several reasons.

  1. It's completely counter-intuitive. Exceptions are designed for exceptional cases. Something working as intended should (we hope) never be an exceptional scenario.
  2. You can't always rely on an exception being thrown and propagated to you. For example, if the exception-throwing code runs in a separate thread, you'll need some extra code to capture it.
  3. It is a potential performance problem. There is an overhead associated with exceptions and if you throw a lot of them, you might see a performance drop in your application.

There are a few more examples and some interesting discussion on this subject here.

Disclaimer: The code above is adapted from the first sample on that wiki page to turn it into C#.



来源:https://stackoverflow.com/questions/3259660/example-of-using-exceptions-to-control-flow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!