我最近写了下面这段代码,其中使用了大量的异常处理。我认为这使得代码看起来非常难以阅读。我可以通过捕获通用的异常来缩短代码,例如
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());
}
}
}
我想知道是否有更好、更简洁的方法来捕获多个异常。