Gee*_*Out 49 java exception-handling exception try-catch
如果发生异常,我有一些我想要执行的代码.但该代码也可以生成异常.但我从未见过人们在另一个try/catch中尝试/捕获.
我正在做不好的练习,也许还有更好的方法:
Uri uri = Uri.parse("some url");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try
{
startActivity(intent);
}
catch (ActivityNotFoundException anfe)
{
// Make some alert to me
// Now try to redirect them to the web version:
Uri weburi = Uri.parse("some url");
try
{
Intent webintent = new Intent(Intent.ACTION_VIEW, weburi);
startActivity(webintent);
}
catch ( Exception e )
{
// Make some alert to me
}
}
Run Code Online (Sandbox Code Playgroud)
这看起来有点尴尬.有什么东西可能有问题吗?
Tom*_*icz 11
编写具有如此多嵌套级别的代码是一种不好的做法,特别是在try-catch- 所以我会说:避免.另一方面,从catch块中抛出异常是不可原谅的罪,所以你应该非常小心.
我的建议 - 将你的catch逻辑提取到一个方法中(所以catch块很简单)并确保这个方法永远不会抛出任何东西:
Uri uri = Uri.parse("some url");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try
{
startActivity(intent);
}
catch (ActivityNotFoundException anfe)
{
// Make some alert to me
// Now try to redirect them to the web version:
Uri weburi = Uri.parse("some url");
Intent webintent = new Intent(Intent.ACTION_VIEW, weburi);
silentStartActivity(webintent)
}
//...
private void silentStartActivity(Intent intent) {
try
{
startActivity(webintent);
}
catch ( Exception e )
{
// Make some alert to me
}
}
Run Code Online (Sandbox Code Playgroud)
您似乎(我可能错了)您正在使用异常来控制程序流.如果投掷ActivityNotFoundException不是特殊情况,则考虑标准返回值,但在正常情况下可能会发生.
| 归档时间: |
|
| 查看次数: |
40871 次 |
| 最近记录: |