3
\$\begingroup\$

I have an SSIS package for SQL Server 2008. In this package, I need to verify that a file exists that matches a pattern of SomeFileName_*.txt where the wild card replaces a YYYYMMDD date. It doesn't matter what the date of the file is, just that any file matching that pattern exists. If a file does not exist, I need to fail the package before using the built in "For each file loop" task. This allows our server to alert me to the package failure.

It's a pretty simple bit of code, but it has a huge smell. I'm catching Exception. I think I'm doing it for the right reasons though. Basically, I'm saying that if any exception gets thrown, fail the script task, and thus the package. Is this a case where it's okay to catch all exceptions??? For reference, these are the possible exceptions that Directory.GetFiles can throw.

Of course, I'm pretty new to , so please let me know if I'm doing anything stupid. (Yes, I know I'm programming in Main, but this is short and sweet. I don't see the harm just this once...)

public void Main()
{

    try
    {
        string sourcePath = Dts.Variables["User::sourcePath"].Value.ToString();
        string searchPattern = Dts.Variables["User::searchPattern"].Value.ToString();

        string[] files = Directory.GetFiles(sourcePath, searchPattern, SearchOption.TopDirectoryOnly);
        if (files.Length > 0)
        {
            Dts.TaskResult = (int)ScriptResults.Success;
        }
        else
        {
            Dts.TaskResult = (int)ScriptResults.Failure;
            Dts.Log(string.Format("No file(s) found in '{0}' with a pattern of '{1}'.", sourcePath, searchPattern), 0, null);
        }
    }
    catch (Exception e)
    {
        Dts.TaskResult = (int)ScriptResults.Failure;
        Dts.Log(string.Format("Script Task encountered an unexpected error. Souce: {0}. Message: {1).", e.Source, e.Message), 0, null);
    }
}
\$\endgroup\$
1
\$\begingroup\$

Yes, it's okay. If you need to catch any exception then you should essentially catch them all.

The reason you typically avoid this and use the most concrete exceptions possible is to provide exception-specific behaviour: an accurate log message or a different continuation once it has been logged.

If all your exceptions are handled the same way then you can just use the catch-all. Note that you can always add a specific handler afterwards because the catch clauses are evaluated linearly.

\$\endgroup\$
  • \$\begingroup\$ I didn't know that they're evaluated linearly. Thanks! \$\endgroup\$ – RubberDuck Oct 24 '14 at 22:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.