-1

I need to know how to handle the exceptions in a situation like below. Please assist me,

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;
            }
        });


    }
}

When I run the above code I need to catch the exception thrown by the Class_B in the Class_A where prints the "ERROR IN CLASS A".

4

2 回答 2

0

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

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

然后像这样使用 ClassBException 在 Class B 的 getMessage 方法中抛出

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

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

于 2012-12-12T12:05:17.773 回答
0

将此方法添加到 A 类:

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

并将执行方法更改为:

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;

   }
于 2012-12-12T12:07:38.847 回答