请考虑以下代码:
using (IRandomAccessStream stream = await storageFile.OpenReadAsync())
{
using (DataReader dataReader = new DataReader(stream))
{
uint length = (uint)stream.Size;
await dataReader.LoadAsync(length);
txtbox.Text = dataReader.ReadString(length);
}
}
storageFile.OpenReadAsync
可能会抛出异常,System.IO.FileNotFoundException
是一种可能的异常类型。 MSDN主题StorageFile.OpenReadAsync
http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.storagefile.openreadasync不包含此方法引发的异常类型列表。如何从文档中找到此信息?我可以捕获Exception
类型,但这是糟糕的编程习惯。
答案 0 :(得分:1)
如果无法找到所有异常列表,我通常会使用VS SDK ErrorHandler.IsCriticalException中的方法:
try
{
// ...
}
catch(Exception e)
{
if (ErrorHandler.IsCriticalException(e))
{
throw;
}
// log it or show something to user
}
您可以反编译Microsoft.VisualStudio.Shell.11.0.dll
以查找异常列表,ErrorHandler将其定义为严重:
对于Windows运行时,我认为验证Exception中的某些HResult值也很好,例如E_OUTOFMEMORY,E_ABORT,E_FAIL等等。
此外,我发现BugSense对于记录异常非常有帮助。我不仅将它用于未处理的异常,而且还用于这样的情况,我不知道这个方法可以抛出什么。它允许使用BugSenseHandler.Instance.LogException
发送自定义日志记录(包括例外),因此我只收集有关不同类型的异常(包括一些意外的HResult异常)的信息,并在每个版本中对我的应用程序进行一些改进。