Java:Try-Catch-Continue? [英] Java: Try-Catch-Continue?

查看:454
本文介绍了Java:Try-Catch-Continue?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我可以一组语句:

  try {
String a = getProperty(a );
String b = getProperty(b);
String c = getProperty(c);
} catch(Exception e){

}

现在,让我们发现没有找到属性b,该函数会抛出异常。在这种情况下,我将如何继续或者将b设置为null,而不必为每个属性编写一个try-catch块?我的意思是,a,b,c存在,但有时候它们可能根本不被发现,在此期间抛出异常。

解决方案

假设您无法更改函数,以便在未找到该属性时返回null,那么您就会将所有内容都包含在自己的try catch块中 - 特别是如果您想要检索的每个值都被检索到(而不是让第一个值失败取消整个操作。)



如果你有很多这些属性要检索,也许写一个更简单的帮助程序使用:

  String getPropertySafely(String key){
try {
return getProperty );
} catch(Exception e){
return null;
}
}


Let's say I can a set of statements:

try {
  String a = getProperty("a");
  String b = getProperty("b");
  String c = getProperty("c");
} catch(Exception e) {

}

Now, lets say property b was not found and the function throws an exception. In this case, how would I just continue or perhaps set b to null without having to write a try-catch block for each property? I mean, a,b,c exist but sometime they might not be found at all during which an exception is thrown.

解决方案

Assuming you can't change the function so that it returns null when the property isn't found, you are kind of stuck wrapping everything in its own try catch block -- especially if you want for every value that can be retrieved to be retrieved (as opposed to letting the first value that fails cancel the whole operation.)

If you have a lot of these properties to retrieve, perhaps it would be cleaner to write a helper method to use:

String getPropertySafely(String key) {
   try {
      return getProperty(key);
   } catch (Exception e) {
      return null;
   }
}

这篇关于Java:Try-Catch-Continue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆