Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching expected exceptions

Tags:

c#

exception

I've got code that looks like this because the only reliable way for me to check if some data is an image is to actually try and load it like an image.

    static void DownloadCompleted(HttpConnection conn) {
        Image img;
        HtmlDocument doc;

        try {
            img = Image.FromStream(conn.Stream);
        } catch {
            try {
                doc = new HtmlDocument();
                doc.Load(conn.Stream);
            } catch { return; }
            ProcessDocument(doc);
            return;
        }
        ProcessImage(img);
        return;
    }

Which looks down right terrible!

What's a nice way of handling these situations? Where you're basically forced to use an exception like an if statement?

like image 603
mpen Avatar asked Nov 20 '25 09:11

mpen


1 Answers

Your logical structure is

if( /* Loading Image Fails */ )
    /* Try Loading HTML */

so I would try to make the code read that way. It would probably be cleanest (though admittedly annoyingly verbose) to introduce helper methods:

bool LoadImage()
{
    Image img;
    try 
    {
        img = Image.FromStream(conn.Stream);
    } 
    catch( NotAnImageException /* or whatever it is */ )
    {
        return false;
    }

    ProcessImage(img);
    return true;
}


bool LoadDocument()
{
   // etc
}

So you can write

if( !LoadImage() )
   LoadDocument();

or extend it to:

if( !LoadImage() && !LoadDocument() )
{
     /* Complain */
}
like image 189
Eric Avatar answered Nov 22 '25 00:11

Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!