2012-05-29 53 views
0

我有这样finally块来表现不同

String str = null; 

try{ 
    ... 
    str = "condition2"; 
}catch (ApplicationException ae) { 
    str = "condition3"; 
}catch (IllegalStateException ise) { 
    str = "condition3"; 
}catch (Exception e) { 
    str = "condition3"; 
} 

if(str == null){ 
    str = "none"; 
} 

现在我想在一行来总结所有str = "condition3";的条件。终于块运行永远不会满足我的需求。还有什么可以做的。

+1

你这是什么意思关键字“总结”? –

+2

我不确定你在寻找什么好处...如果你想让错误字符串对所有3个例外都是相同的,那么使用下面的答案。如果没有,并且在我们没有看到的每个异常块中都有更多的代码,那么我不会看到重复一行很糟糕。 – billjamesdev

+0

这是什么意思“all str =”condition3“?如果你想总结所有str,它将包含cond2和三个例外中的一个 –

回答

6

从Java 7开始,您可以在单个catch块中使用catch multiple exception types。该代码看起来是这样的:

String str = null; 

try { 
    ... 
    str = "condition2"; 
} catch (ApplicationException|IllegalStateException|Exception ex) { 
    str = "condition3"; 
} 

BTW:你已经发布的代码,以及我的Java 7的代码可以全部折叠成简单catch (Exception e),因为ExceptionApplicationExceptionIllegalStateException的超类。

+3

但是这并不是毫无意义,因为前两个扩展了'Exception'?只要他这么做,他就应该抓住Exception。 –

+0

我猜他没有在那里显示所有的代码,所以像这样分组他们可能不会起作用。 – billjamesdev

+0

@PaulBellora:是的。但OP的等效Java 6代码也是如此。我只是在演示语法。不过,我会添加一个关于这个的注释。 – Asaph

2

您可以使用Java 7异常处理语法。 Java 7在一个catch块中支持多个异常处理。经验 -

String str = null; 

try{ 
    ... 
    str = "condition2"; 
}catch (ApplicationException | IllegalStateException | Exception ae) { 
    str = "condition3"; 
} 
+0

我不想分组异常,因为每个异常将有一个单独的消息等 –

+0

在这种情况下,你将不得不遵循传统的try catch块。尝试{ ... str =“condition2”; (ApplicationException ae){ } str =“condition3”; (IllegalStateException ise){ str =“condition3”; (例外e){ str =“condition3”; } –

1
try{ 
    ... 
    str = "condition2"; 
}catch (Exception ae) { 
str = "condition3"; 
} 

至于其他都是异常的子类。如果你想显示不同的信息,那么可以尝试如下

try{ 
    ... 
    str = "condition2"; 
}catch(ApplicationException | IllegalStateException e){ 
if(e instanceof ApplicationException) 
    //your specfic message 
    else if(e instanceof IllegalStateException) 
    //your specific message 
    else 
     //your specific message 
    str = "condition3"; 
} 
+0

是的,他们是子类,但我想为每个子例外打印不同的消息。 –

+1

@imran tariq相应地编辑你的问题 – Maddy

+0

@imrantariq看到我编辑的答案。 –

0

正如你在ApplicationExceptionIllegalStateException catch块和一般例外Exception catch块做同样的事情,那么你就可以删除ApplicationExceptionIllegalStateException块。

0

我要去这里走出去的肢体,并提供这样的:

String str = null; 

try{ 
    ... 
    str = "condition2"; 
}catch (Throwable e) { 
    str = "condition3"; 
} 
finally { 
    if(str == null){ 
     str = "none"; 
    } 
} 

如果这不是你所说的“总结”,那么请澄清是什么意思。

请仔细阅读

http://www.tutorialspoint.com/java/java_exceptions.htm http://docs.oracle.com/javase/tutorial/essential/exceptions/

+0

你不觉得应该有一个像catch这样的块吗? –

+0

解释“catchFinally” –

+0

catch最后将是一个只会在catch语句后执行的块。 –

1

您必须添加“最终”,如果您使用的是单catch块捕获多个例外的Java 7的功能

catch (final ApplicationException|IllegalStateException|Exception ex) {