高抽象级别方法中的异常

时间:2011-05-28 22:04:45

标签: java exception-handling design-patterns

方法执行多项任务:

public void method () {

    try {
         task1(); //may throw sql exception
         task2(); //may throw sql exception
         task3(); //may throw sql exception
   } catch (SQLException se) {
       //from which line cames the exception?
   }

我正在寻找在这些情况下采用的标准。
目前我的想法是这样的:
1)如果我需要采取一些行动取决于抛出异常的特定行,唯一的事情是使用他自己的try-catch来表达每个语句;示例中有三个。
2)如果我不需要根据抛出异常的行采取特定的操作,那么堆栈跟踪将提供足够的信息来知道行没有针对每条指令的try-catch块而出错,这使得代码不易读取。

2 个答案:

答案 0 :(得分:2)

stacktrace将包含所有必要的信息。

如果您需要采取特定操作,那么在每个taskX()方法中,您可能希望抛出一个不同的异常,包装SQLException。同样冗长。

答案 1 :(得分:0)

你可以保留一个计步器

int step = 0;
try {
     task1(); //may throw sql exception
     step=1;//got through first
     task2(); //may throw sql exception
     step=2;
     task3(); //may throw sql exception
} catch (SQLException se) {
   //from which line cames the exception?
   if(step=0){
     //didn't get through first task
   }
   if(step=1){
     //didn't get through second task
   }
   if(step=2){
     //didn't get through third task
   }
}