main returning errorlevel & exceptions

J

Jeroen

Here's the situation. My program will be able to start with an argument
(a path to a file) and then run a batch of commands in that file. So if
an argument is provided to the main method, the program logic moves to
the classes/methods that execute the batch (instead of s normal, GUI
driven program execution).

Should an error occur somewhere during the batch, I really need to
catch it, so that I can return my main method with an errorlevel. But
at the same time, I would like to rethrow any exception I cannot
handle. So here's the problematic code:

//------------------------------------------------------------
public int Main(string[] args)
{
return RunScript(args[0]);
}
//------------------------------------------------------------
public int RunScript(string filepath)
{
try
{
// Do dangerous stuff.
}
catch (System.Exception exc)
{
if (exc is MyHandledException)
{
// Do intelligent stuff.
}
else
{
return 1;
throw exc;
}
}
}
//------------------------------------------------------------

Is the final part even ok? Do I need the Finally statement for this?

Your thoughts.
 
J

Jianwei Sun

A couple of suggestions :

1> return 1;
throw exc;

I don't think the throw exc will ever be executed, it's unreachable code.

2> You shouldn't catch System.Exception exc , and determine the type
again, you really should do something like

try
{
}
catch(MyHandledException myHandleException)
{
}
catch(MyOtherExcetion otherException)
{
}
catch(Exception )
{
rethrow here..
}

3> There are 2 ways to error handling, returning value and exception.
The suggested way is not to mix them..

By setting and checking some properties on the exception object, you
should avoid using the return value.
 
J

Jeroen

Thanks for the reaction. I think I will (A) handle whichever exception
i can with a messagebox followed by returning the Main method with an
errorlevel and (B) rethrow any unhandled exception.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top