【发布时间】:2015-09-13 00:52:01
【问题描述】:
我最近写了以下代码;它使用了大量的异常处理。我认为它使代码看起来非常不可读。我可以通过捕获通用异常来缩短代码,例如
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());
}
}
}
我想知道是否有更好更简洁的方法来捕获多个异常。
【问题讨论】:
-
对不起,我复制粘贴的时候不小心把它删了
-
您的问题似乎是在寻求一种万能的解决方案,而我认为这种解决方案不存在。异常处理细节将取决于程序本身的需求和结构。
-
好吧,我会说您捕获了一个一般异常,然后使用 if 语句来确定哪个异常是哪个异常并执行相应的操作。这样你只需要一个捕获。 (如果这是你想要的)
-
一篇关于这个主题的好文章:stackify.com/best-practices-exceptions-java