c# - 在应用程序的发布版本中保留 try/catch 块
问题描述
我有一个移动应用程序,将放在应用程序商店并供消费者使用,这是我以前从未经历过的过程。我想知道我是否应该在处理上传文件的应用程序部分使用 try/catch 块。我想在文件没有上传的情况下使用它 - 而不是使应用程序崩溃,使用 try/catch 块将允许用户被通知他们的文件尚未上传。
这是好习惯吗?提醒用户注意这一点似乎是明智的,而不是在发生这种情况时关闭应用程序。我不确定 try/catch 是否是最好的方法,或者你们中的任何人是否会推荐更好的策略。
我在想我会做这样的事情:
try
{
UploadFile(byte[] file)
}
catch
{
await DisplayAlert("The file has failed to upload.");
}
任何建议将不胜感激
解决方案
是的,这是一个很好的方法。无论如何,用户应用程序都不应该崩溃,try/catch
这是避免它的好习惯。
当然,您可以使用if/then
和try/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
}
您不应该尝试处理所有可能的异常(有数百个!),但是您可以预测哪些异常更有可能被抛出并相应地处理它们。
推荐阅读
- r - 带有ggplot的for循环-rep_len(TRUE,nrow(x))中的错误:无效的'length.out'值
- azure-functions - 如何在 Visual Studio 2019 和 .NET 5 隔离的不同端口上运行 ISOLATED Azure Function 应用程序
- sql-server - Docker 中的 web api 无法连接到主机上的 SQL Server,出现登录前握手错误
- blazor - Blazor OIDC 身份验证弹出窗口
- javascript - 调整 css 规则大小更改其他 div
- c# - 无法从程序集“System.ServiceModel”加载类型“System.ServiceModel.Description.MetadataConversionError”
- c++ - 即使设置路径,Mingw 也存在问题
- php - WordPress 主题 functions.php $wpdb->insert 创建重复项
- javascript - 如何在按键后跳转,向上箭头,
- python - 使用 pandas 中的列子集