Java - 在try/catch中进行try/catch是不好的做法吗?

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)

这看起来有点尴尬.有什么东西可能有问题吗?

T.J*_*der 40

没关系,但如果你的异常处理逻辑很复杂,你可以考虑将它分解为自己的函数.


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不是特殊情况,则考虑标准返回值,但在正常情况下可能会发生.

  • “这么多级别?” 我总共看到三个。他在catch块中的逻辑并不比在try块中的if块深。 (2认同)

Pea*_*Gen 5

答案是否定的..它是 100% 好的.. 你可能不得不在 JDBC 和 IO 中使用很多这些,因为它们有很多异常要处理,一个在另一个里面......