2012-11-14 53 views
18

我有一个声明,引发了很多检查异常。我可以添加所有catch块的所有的人都像这样:是否有可能捕获除运行时异常外的所有异常?

try { 
    methodThrowingALotOfDifferentExceptions(); 
} catch(IOException ex) { 
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex); 
} catch(ClassCastException ex) { 
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex); 
} catch... 

我不喜欢这一点,因为他们都在处理相同的方式,以便有一种重复的代码,也有大量的代码编写。相反,能赶上Exception

try { 
    methodThrowingALotOfDifferentExceptions(); 
} catch(Exception ex) { 
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex); 
} 

这将是确定的,但我希望所有运行时异常被丢弃而不被卡住。有没有解决这个问题的方法?我在想,要捕捉的异常类型的一些聪明的泛型声明可能会诀窍(或者可能不会)。

回答

40

你可以做到以下几点:

try { 
    methodThrowingALotOfDifferentExceptions(); 
} catch(RuntimeException ex) { 
    throw ex; 
} catch(Exception ex) { 
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex); 
} 
+2

很好的答案... +1 – Juvanis

+2

+1很酷。不是我见过的最干净的,但是有诀窍。 – drasto

11

如果你可以使用Java 7,你可以使用一个Multi-Catch

try { 
    methodThrowingALotOfDifferentExceptions(); 
} catch(IOException|ClassCastException|... ex) { 
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex); 
} 
+0

+1警告我Java 7中这个新的有价值(且已逾期的IMO)功能 –

+0

+1由于这个原因,我会尽可能使用Java 7。但我不能,我很抱歉,因为这种Multi-Catch是完美的。我必须使用Java 6:(((( – drasto

1

你可以尝试这样的事情,基本上赶上一切,然后如果它是该类的实例,则重新抛出RuntimeException ...

try { 
    methodThrowingALotOfDifferentExceptions(); 
} catch(Exception ex) { 
    if (ex instanceof RuntimeException){ 
     throw ex; 
    } 
    else { 
     throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex); 
    } 
} 

眼见仿佛这将是凌乱写一遍又一遍(和坏的可维护性),我的代码可能会转移到不同的等级,这样的事情...

public class CheckException { 
    public static void check(Exception ex, String message) throws Exception{ 
     if (ex instanceof RuntimeException){ 
      throw ex; 
     } 
     else { 
      throw new MyCustomInitializationException(message, ex); 
     } 
    } 
} 

而且用它你这样的代码......

try { 
    methodThrowingALotOfDifferentExceptions(); 
} catch(Exception ex) { 
    CheckException.check(ex,"Class Resolver could not be initialized."); 
} 

注意到我们通过在message,使我们仍然可以自定义我们的MyCustomInitializationException

+0

)如果我需要多次执行它,最后一个选项会很好,但这不是我的情况 - 我只需要使用它一次。只有我将String的参数化为静态方法'message。 – drasto

+0

你需要在代码中将'ex'转换为'RuntimeException'。 –