Wednesday, 11 February 2009

Continue next step after exception

In some case it is handy to catch the exception and then continue with the next step right after the line that threw the exception.
There are several ways to do this, one is writing a try {} catch{} block around every line of code (which will of course pollute your code).

I found some code bits on the internet, which wrap this in a function.
I created a new Console application to demonstrate this.

First we create a class handling this functionality:

public static class Executer
{
public static void Execute(Action action, string errorMessageToLog)
{
try
{
action();
}
catch
{
Console.WriteLine(errorMessageToLog);
}
}
}


Then we create the code in the Main function of our console application:


static void Main(string[] args)
{
for (int counter = 10; counter > -10; counter--)
{
Executer.Execute(() =>
Console.WriteLine((10 / counter).ToString()), "Error Occured");
}
Console.Read();
}


When we run the code, you will notice that when counter = 0, a division by zero will occur, so this will throw an error. This error is displayed to the console and the next value of counter will be processed.

No comments:

Post a Comment