首页 > 解决方案 > 在应用程序的发布版本中保留 try/catch 块

问题描述

我有一个移动应用程序,将放在应用程序商店并供消费者使用,这是我以前从未经历过的过程。我想知道我是否应该在处理上传文件的应用程序部分使用 try/catch 块。我想在文件没有上传的情况下使用它 - 而不是使应用程序崩溃,使用 try/catch 块将允许用户被通知他们的文件尚未上传。

这是好习惯吗?提醒用户注意这一点似乎是明智的,而不是在发生这种情况时关闭应用程序。我不确定 try/catch 是否是最好的方法,或者你们中的任何人是否会推荐更好的策略。

我在想我会做这样的事情:

try
{
   UploadFile(byte[] file)
}

catch
{
  await DisplayAlert("The file has failed to upload.");
}

任何建议将不胜感激

标签: c#iosxamarinxamarin.forms

解决方案


是的,这是一个很好的方法。无论如何,用户应用程序都不应该崩溃,try/catch这是避免它的好习惯。

当然,您可以使用if/thentry/catch块组合通常的检查。例如,如果没有互联网连接,用户显然无法上传文件。所以你可以写

try
{
   if (InternetConnectionPresent())
       UploadFile(byte[] file);
   else
       await DisplayAlert("Please check your internet connection.");
}

catch
{
  await DisplayAlert("The file has failed to upload.");
}

此外,try/catch块为您提供了分析应用程序意外行为的额外可能性。例如,您可以使用Microsoft 的分析中心,因此您的catch部分将如下所示:

using Microsoft.AppCenter.Crashes; // you need to add this package to your project
.....
catch (Exception e)
{
  var dictionaryCrash = new Dictionary<string, string>
  {
       {  "additional information", _any_info_you_want_to_know_ }
  };
  Crashes.TrackError(e, dictionaryCrash);
  await DisplayAlert("The file has failed to upload.");
}

更新:

正如评论中提到的,最好在不同的部分处理不同的异常,例如:

try
{
...
} 
catch (NetworkException e)
{
  // something wrong with connection
}
catch (AutenticationException e)
{
  // bad login
}
catch (IOException e)
{
  // something wrong with disk
}
catch (Exception e)
{
  // all others exceptions
}

您不应该尝试处理所有可能的异常(有数百个!),但是您可以预测哪些异常更有可能被抛出并相应地处理它们。


推荐阅读