Java异常处理的最佳实践

前端之家收集整理的这篇文章主要介绍了Java异常处理的最佳实践前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我最近写了下面的代码;它使用了很多异常处理.我认为它使代码看起来非常难以理解.我可以通过捕获泛型异常来缩短代码,例如
  1. catch (Exception e){
  2. e.printStackTrace();
  3. }

但我也听说过捕获一般异常不是一个好的编码实践.

  1. public class DataAnalyzerTester {
  2. /**
  3. * @param args args[0] stores the filename
  4. * @exception NoSuchElementException if user attempts to access empty list element
  5. * @exception ArithmeticException if user attempts to divide by 0
  6. * @exception ArrayIndexOutOfBoundsException if user supplied less than 3 arguments
  7. * @exception IOException problems with creating and writing files
  8. * @exception RuntimeException if user attempts to pass empty list to constructor
  9. */
  10. public static void main(String[] args) {
  11.  
  12. try{
  13. //some code
  14.  
  15. } catch (NoSuchElementException e) {
  16. System.out.println("Accessing element that does not exist: " + e.toString());
  17. } catch (ArithmeticException e) {
  18. System.out.println("Division by zero: " + e.toString());
  19. } catch (ArrayIndexOutOfBoundsException e) {
  20. System.out.println("Please supply a command line arguement that specifies your file path: " + e.toString());
  21. } catch (IOException e) {
  22. System.out.println("Other IO errors: " + e.toString());
  23. } catch (RuntimeException e) {
  24. System.out.println(e.toString());
  25. }
  26. }
  27. }

我想知道是否有更好,更清晰的方法来捕获多个异常.

解决方法

首先,除非你有充分的理由,否则永远不会捕获RuntimeException,Exception或Throwable.这些将捕获大多数抛出的东西,Throwable将捕获所有内容,甚至是那些你不想捕获的东西,比如OutOfMemoryError.

其次,避免捕获运行时异常,除非它直接阻碍程序的关键操作. (但严重的是,如果有人看到你发现了NullPointerException,那么他们完全有权在你身上打电话给你.)你唯一需要注意的例外是那些你需要处理的例外.在您的异常列表中,您唯一应该打扰的是IOException.其余的是没有足够的测试或草率编码的结果;那些不应该在您的应用程序的正常运行时间内发生.

第三,在Java 7中,如果异常是互斥的,您可以为异常执行multi-catch语句.链接的示例很好地解释了它,但如果您遇到同时抛出IOException和sqlException的代码,您可以像这样处理它:

  1. try {
  2. // Dodgy database code here
  3. catch (IOException|sqlException ex) {
  4. logger.log(ex);
  5. throw ex;
  6. }

这会清理一些事情,因为你没有笨拙和庞大的异常链.

猜你在找的Java相关文章