Java – 在try / catch中执行try / catch是不好的做法吗?

我有一些代码,如果发生exception,我想执行。 但是那个代码也会产生一个exception。 但是我从来没有见过人们在另一个尝试/抓住里面试一试。

是我做的不好的做法,也许有这样做的一个更好的方法:

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 } } 

看起来有些尴尬。 有什么可能是错的吗?

谢谢!

没关系,虽然如果你的exception处理逻辑很复杂的话,你可以考虑把它分解成它自己的函数。

编写具有如此多嵌套级别的代码是一个不好的做法,特别是在try-catch – 所以我会说:避免。 另一方面,从catch块中抛出一个exception是不可原谅的,所以你应该非常小心。

我的build议 – 将你的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 } } 

也似乎(我可能是错误的),你正在使用exception来控制程序stream程。 如果抛出ActivityNotFoundException exception,请考虑标准返回值,但在正常情况下可能会发生这种情况。

答案是否定的。它是100%的..你可能不得不在JDBC和IO中使用很多这些,因为它们有很多例外需要处理,一个在另一个之内。

如果你不想使用嵌套尝试和捕获,这里是替代解决scheme,你也可以这样做:

  boolean flag = false; void test(); if(flag) { test2(); } 

testing方法在这里:

 private void test(){ try { Uri uri = Uri.parse("some url"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); }catch (ActivityNotFoundException anfe){ System.out.println(anfe); flag =true; } } 

现在把第二种方法中的其余代码:

 public void test2(){ 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 }