开发者

Including paramaters only for the purpose of exception reporting in inner functions

CreateDocument(string templatePath)
{
    Document doc = OpenDocument(templatePath);
    Picture pic = GetLogo();
    AddLogo(doc, pic, templatePath);
}

AddLogo(Document doc, Picture logo, string templatePath)
{
    Picture placeholder = doc.FindLogoPlaceholder();
    if (placeholder.Size != logo.Size)
    {
        throw new ApplicationException(
            String.Format("Invalid template {0}, logo size: {1}, required: {2}",
                 templatePath, placeholder.Size, logo.Size
            ));
    }
}

Consider the above code as an example I just made up.

Notice that the only reason templatePath is passed into the AddLogo method is to facilitate exception generation.

I have something in my code today where I needed to do this, and it feels like a really nasty co开发者_运维知识库de smell to me. But I'm not too familiar with exception handling patterns and I don't really see any better way to do it.

I'm wondering what your thoughts are and if there is a better pattern to dealing with situations like this.


Create the exception on a higher level:

CreateDocument(string templatePath)
{
    Document doc = OpenDocument(templatePath);
    Picture pic = GetLogo();
    try {
        AddLogo(doc, pic);
    } catch (InvalidLogoSize e) {
        throw new ApplicationException(
            String.Format("Invalid template {0}, logo size: {1}, required: {2}",
                 templatePath, e.pSize, e.lSize
            ));
    }
}

AddLogo(Document doc, Picture logo)
{
    Picture placeholder = doc.FindLogoPlaceholder();
    if (placeholder.Size != logo.Size)
    {
        throw new InvalidLogoSizeException(placeholder.Size, logo.Size);
    }
}


You would typically throw the exception, then catch it at any layer where you can add more information, wrap it in a new exception and throw that one.


The caller of the function can catch an rethrow with additional information:

CreateDocument(string templatePath) 
{ 
    Document doc = OpenDocument(templatePath); 
    Picture pic = GetLogo(); 
    try
    {
        AddLogo(doc, pic);
    }
    catch(Excpetion e)
    {
        throw new ApplicationException( templatePath, e);
    }
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜