This is a question of what the ‘best practice’ is for declaring new variables, and I’ve seen this situation a few times now. I have a class whose constructor reads a config file, eg:
ConfigMgr config = new ConfigMgr(args[0]);
Of course, if you run the console app without that argument, an exception results. If I surround that line with a try/catch as follows, I get the error ‘The name ‘config’ does not exist in the current context’. Understandable.
try
{
ConfigMgr config = new ConfigMgr(args[0]);
}
catch
{
Console.WriteLine("Config file not specified or incorrect in format. Exiting.");
Console.ReadLine();
}
// Defaults
string aucomposingfile = config.getValue("aucomposingfile");
string nzcomposingfile = config.getValue("nzcomposingfile");
...etc
I could separate out the part that requires the argument in the constructor – do the new ConfigMgr part outside the try/catch block, then do something like config.LoadFile() in the try/catch. But I can’t imagine that’s what those in the know do.
Any thoughts?
Thanks!
There is no reason why you cannot do this:
Of course the arguably more correct way may be to check the command line arguments before attempting to use them, and throw a specific exception if they don’t meet your requirements – you depend on them, so verify them first. This has a better code flow than just trying to use them and catching an exception. This way your
catchblock becomes more focused on problems more specific to the config file, rather than handling issues with the command line arguments as well.