Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of "using exceptions to control flow" [closed]

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

like image 727
GurdeepS Avatar asked Jul 15 '10 20:07

GurdeepS


People also ask

Can Exception Handling be used for flow control?

According to many references like here and here, using Exceptions to control application flow is an anti-pattern that is not recommended. (Because of performance issues, Less readable and etc).

What is control flow in exceptions in Java?

The statements in the code are executed according to the order in which they appear. However, Java provides statements that can be used to control the flow of Java code. Such statements are called control flow statements. It is one of the fundamental features of Java, which provides a smooth flow of program.


1 Answers

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.

like image 65
Eric Olsson Avatar answered Sep 23 '22 19:09

Eric Olsson