Try/catch Image.FromStream() 没有捕捉到 using 语句的其余部分?

Try/catch Image.FromStream() without catching the rest of the using statement?

Image.FromStream 在您上传非图像内容时抛出 InvalidArgumentException

因此我有类似这样的代码:

public void ActionMethod()
{
    try
    {
        using ( var image = Image.FromStream(httpPostedFileBase.InputStream) )
        {
            MoreStuffToDo(image);
        }
    }
    catch (InvalidArgumentException e)
    {
        ModelState.AddModelError( "", "File is not a valid image" );
    }
}

问题是 InvalidArgumentException 也会捕获与 Image.FromStream 无关的内容,即 MoreStuffToDo()

我能想到的唯一解决办法就是去掉using语句。但这听起来也是个糟糕的决定。

正确的做法是什么?所以我们在 Image.FromStream() 方法周围有一个 try/catch 并且确定图像在所有情况下都得到了正确处理?

这不是 using that's important... it's the call to IDisposable.<a href="https://msdn.microsoft.com/en-us/library/system.idisposable.dispose(v=vs.110).aspx" rel="nofollow">Dispose()</a>using 在幕后为您进行调用,让您可以简单地写下:

using(var x = new X())
{
    // do stuff with x
}

... 而不是这个:

X x = null;
try
{
    x = new X();
    // do stuff with x
}
finally
{
    if(x != null)
    {
        x.Dispose(); // clean up resources
    }
}

这是跳过一堆样板代码的好方法,但您绝不会被迫使用它。您可以显式调用 IDisposable.Dispose() 并让自己更好地控制发生的情况:

public void ActionMethod()
{
    // declare image...
    Image image = null;

    try
    {
        // attempt to load image from stream...
        image = Image.FromStream(httpPostedFileBase.InputStream)
    }
    catch
    {
        // failed to load image from stream...
        ModelState.AddModelError( "", "File is not a valid image" );
        // exit
        return;
    }

    try
    {
        // perform additional processing...
        MoreStuffToDo(image);
    }
    catch
    {
        // handle errors from MoreStuffToDo()
    } 
    finally
    {
        // clean up image...
        image.Dispose();
    }
}