Thursday, September 22, 2011

Getting more information than the exception class provides

We recently had a question about how to get more information than an exception’s type provides. The developer was trying to copy a file and didn’t know why the copy was failing. File copies can fail for many reasons, almost all of them what Eric Lippert calls “exogenous conditions”. The developer was catching System.IOException and parsing the error message. It worked on his machine, but failed during test passes.

Unfortunately, the .NET Framework doesn’t always directly provide the reason that the file copy failed. If an error results from an IO operation the .NET Framework will call GetLastError to find out why the operation failed, then throw an IOException with a message explaining the problem: sharing violation, path too long, etc. The error message is formatted in such a way that you can expose it directly to your user: it clearly states the problem and gets translated into the user’s OS language.

This is a little annoying if you’re trying to programmatically respond to the error. For example, if there’s a sharing violation you might want to wait for a few seconds then try again. How do you tell that this IOException comes from a sharing violation as opposed to a disconnected USB drive or a network failure?

You do NOT want to parse the exception message because exception messages get translated into the user’s OS language. You can’t programmatically parse a localized string without doing a lot of unnecessary work. Moreover, the exception message could change slightly between different versions of the .NET Framework. While we don’t rewrite exception messages just for fun, one day someone could complain that the error is slightly misleading and we’d fix it, breaking your parsing code. So what can you do if you want a more robust way to get more information than the exception code gives you?

The answer is pretty simple: call Marshal.GetLastWin32Error yourself in your catch block and look up the system error code on MSDN. Reading the error doesn’t clear it so you can call GetLastWin32Error even after the Framwork API does.

Read more: .NET Blog
QR: getting-more-information-than-the-exception-class-provides.aspx

Posted via email from Jasper-Net