在Java中正确的错误处理

时间:2012-12-12 11:59:14

标签: java exception-handling

我需要知道如何在下面的情况下处理异常。请帮助我,

public interface DCommand {

    public Object execute(Class_A car);
}

public class Class_B {

    public void getMessage() throws Exception {       
            throw new Exception("Test error");
    }
}

public class Class_A {

    Class_B cb = null;

    public Class_B getClass_b() {
        cb = new Class_B();
        return cb;
    }

    public Object testAction(DCommand command) {
        Object returnObject = null;
        try {
            return (Boolean) command.execute(this);
        } catch (Exception e) {
            System.out.println("ERROR IN CLASS B" + e.getLocalizedMessage());
        }

        return returnObject;
    }
}


====================== simiulating ============================

public class Test {

    public static void main(String[] args) {
        Class_A c = new Class_A();

        boolean a = (Boolean) c.testAction(new DCommand() {

            @Override
            public Object execute(Class_A car) {
                try {
                    car.getClass_b().getMessage();
                    return true;
                } catch (Exception ex) {
                    System.out.println("Error in the simulator.");
                }
                return false;
            }
        });


    }
}

当我运行上面的代码时,我需要捕获Class_A中Class_B抛出的异常,其中打印出“ERROR IN CLASS A”。

2 个答案:

答案 0 :(得分:0)

问题是你在B类的getMessage方法中抛出了一种异常。相反,您应该通过扩展java.lang.Exception来定义自己的例外。

public class ClassBException extends Exception {
   public ClassBException(String msg) {
      super(msg);
   }
}

然后使用ClassBException抛出类B的getMessage方法,就像这样

public class Class_B {
    public void getMessage() throws ClassBException {       
            throw new Exception("Test error");
    }
}

现在,您需要在调用Class B的getMessage方法的任何地方为ClassBException设置单独的catch块。

答案 1 :(得分:0)

将此方法添加到A类:

public void runGetMessage()
{
   try{
     cb.getMessage();
   }catch(Exception e){
      System.out.println("Error in CLASS A.");
   }
}

并将Execute方法更改为:

public Object execute(Class_A car) {
    try {
          car.getClass_b();
          car.runGetMessage();
          return true;
    } catch (Exception ex) {
          System.out.println("Error in the simulator.");
    }
    return false;

   }