推迟执行try-catch

时间:2012-05-17 14:30:10

标签: java blackberry blackberry-jde

是否可以推迟按钮点击时触发的try-catch的执行。 我厌倦了尝试各种方法。没有成功。

假设我有一个按钮。在按钮上单击字段更改侦听器,将执行这些try catch语句。

    ButtonField showInputButton = new ButtonField(" Search ",ButtonField.FIELD_HCENTER | ButtonField.CONSUME_CLICK);
      showInputButton.setChangeListener(new FieldChangeListener() 
      {

            public void fieldChanged(Field field,int context) 
            {
                    Dialog.alert(TextField1.getText());
                //Here there are some code snippets for jumping to another form
                  try
                  {   
                    //Some statements that filter data from database
                  }
                  catch( Exception e ) 
                    {         
                        System.out.println( e.getMessage() );
                        e.printStackTrace();
                    }
            }
        }

                    );

      add(showInputButton);

这并不是说我根本不想要执行这些语句。但是我希望在遇到try-catch块之前的某些操作后执行它们。

这种事情是否可行。请指导。

enter image description here

我首先要感谢所有回应他们建议的人。我为无法清楚地解释我的问题而道歉,因为我在这些try catch语句中做了什么,以及是什么让我推迟了try-catch块。 请根据我的具体要求找到附图。

重新编辑

我在通过建议增强了建议的代码之后添加了下面的图片,并且还展示了我以编程方式尝试的内容。如果图像不清晰,请通知。

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以将异常保存为变量以供日后使用...

Exception savedException;
try {   
   //Some statements that filter data from database
}
catch( Exception e ) {         
  savedException = e;
}

// do more stuff then deal with exception afterward
throw savedException;

答案 1 :(得分:0)

您可以启动一个线程并等待您正在寻找的条件发生(您可能必须在满足该信息时向线程发出信号)

伪代码:

static boolean isConditionMet = false;

public void fieldChanged(Field field,int context)  // inside the ButtonField
{
  Thread thread - new Thread() {
    public void run() {
      // TODO: wait for condition using isConditionMet
      // TODO: perform desired actions when condition happens
      // TODO: reset isConditionMet
    }
  };
  thread.start(); 
}

你当然需要在某处设置isConditionMet,你可以测试/识别你正在寻找的条件是真的。您还需要使用某种Lock / Semaphore / Monitor保护对isConditionMet的访问,以防止同时访问。