Java 最后,阻止不同的行为
我有这样的情况Java 最后,阻止不同的行为,java,try-catch,try-catch-finally,finally,Java,Try Catch,Try Catch Finally,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 =
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”代码>在一行中。因为最后一块总是跑,所以不能满足我的需要。还可以做些什么。从Java7开始,您可以在一个块中捕获。代码如下所示:
String str = null;
try {
...
str = "condition2";
} catch (ApplicationException|IllegalStateException|Exception ex) {
str = "condition3";
}
顺便说一句:您发布的代码以及我的Java 7代码都可以简单地折叠成catch(Exception e)
,因为它是and的超类。您可以使用Java 7异常处理语法。Java7支持在一个catch块中处理多个异常。经验
String str = null;
try{
...
str = "condition2";
}catch (ApplicationException | IllegalStateException | 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";
}
当您在ApplicationException
和IllegalStateException
捕获块中以及在general exceptionexception
捕获块中执行相同的操作时,您可以删除ApplicationException
和IllegalStateException
块。我将在这里冒险,并提供以下内容:
String str = null;
try{
...
str = "condition2";
}catch (Throwable e) {
str = "condition3";
}
finally {
if(str == null){
str = "none";
}
}
如果这不是你所说的“总结”,那么请澄清
请阅读
如果使用Java 7在单个catch块中捕获多个异常的功能,则必须添加“final”关键字
catch (final ApplicationException|IllegalStateException|Exception ex) {
你说的“总结”是什么意思?我不知道你想要什么好处。。。如果希望所有3个异常的错误字符串相同,请使用以下答案。如果没有,并且在我们没有看到的每个异常块中都有更多的代码,那么我不认为重复一行就那么糟糕。“all str=“condition3”是什么意思?如果你想把所有str相加,它将由cond2和三个异常组成。@Bill James:在所有这些之后。仅我不认为重复一句话就那么糟糕“这个想法对我有用。我认为这个‘要求’是一个更大问题的证据。更可能的情况是,您应该让异常传播,而不是根据是否获得异常来分配特殊值。那么,str
究竟是如何成为空值的呢?但是自从前两个扩展异常以来,这难道不是毫无意义的吗?只要他这样做,他就应该捕获异常。我猜他没有在那里显示所有的代码,所以这样分组可能不起作用。@PaulBellora:是的。但OP的等效Java6代码也是如此。我只是在演示语法。尽管如此,我还是要补充一点。Catch(ApplicationException | IllegalStateException | Exception):是否有必要将异常保留在那里。。。。。。。。由于它是超类,我的意思是,如果您想为每种异常类型打印不同的消息,那么仅使用异常就足够了,你需要做你在原始问题中发布的三个不同的块。我不希望分组异常,因为每个异常都会有单独的消息。在这种情况下,你必须遵循传统的try-catch块。请尝试{…str=“condition2”}catch(ApplicationException ae){str=“condition3”}catch(非法状态异常ise){str=“condition3”}catch(异常e){str=“condition3”}是的,它们是子类,但我想为每个子异常打印不同的消息。catchFinally将是一个仅在catch语句之后执行的块。
catch (final ApplicationException|IllegalStateException|Exception ex) {