我最近写了下面的代码;它使用了很多异常处理.我认为它使代码看起来非常难以理解.我可以通过捕获泛型异常来缩短代码,例如
- catch (Exception e){
- e.printStackTrace();
- }
但我也听说过捕获一般异常不是一个好的编码实践.
- public class DataAnalyzerTester {
- /**
- * @param args args[0] stores the filename
- * @exception NoSuchElementException if user attempts to access empty list element
- * @exception ArithmeticException if user attempts to divide by 0
- * @exception ArrayIndexOutOfBoundsException if user supplied less than 3 arguments
- * @exception IOException problems with creating and writing files
- * @exception RuntimeException if user attempts to pass empty list to constructor
- */
- public static void main(String[] args) {
- try{
- //some code
- } catch (NoSuchElementException e) {
- System.out.println("Accessing element that does not exist: " + e.toString());
- } catch (ArithmeticException e) {
- System.out.println("Division by zero: " + e.toString());
- } catch (ArrayIndexOutOfBoundsException e) {
- System.out.println("Please supply a command line arguement that specifies your file path: " + e.toString());
- } catch (IOException e) {
- System.out.println("Other IO errors: " + e.toString());
- } catch (RuntimeException e) {
- System.out.println(e.toString());
- }
- }
- }
我想知道是否有更好,更清晰的方法来捕获多个异常.
解决方法
首先,除非你有充分的理由,否则永远不会捕获RuntimeException,Exception或Throwable.这些将捕获大多数抛出的东西,Throwable将捕获所有内容,甚至是那些你不想捕获的东西,比如OutOfMemoryError.
其次,避免捕获运行时异常,除非它直接阻碍程序的关键操作. (但严重的是,如果有人看到你发现了NullPointerException,那么他们完全有权在你身上打电话给你.)你唯一需要注意的例外是那些你需要处理的例外.在您的异常列表中,您唯一应该打扰的是IOException.其余的是没有足够的测试或草率编码的结果;那些不应该在您的应用程序的正常运行时间内发生.
第三,在Java 7中,如果异常是互斥的,您可以为异常执行multi-catch语句.链接的示例很好地解释了它,但如果您遇到同时抛出IOException和sqlException的代码,您可以像这样处理它:
- try {
- // Dodgy database code here
- catch (IOException|sqlException ex) {
- logger.log(ex);
- throw ex;
- }
这会清理一些事情,因为你没有笨拙和庞大的异常链.