我做了一个计算器程序,能随意进行四则运算,但感到不很完美,想让在输入两个数或运算符时,如果不合法,就弹出对话框提示,但我还不会用try except句子,看书试了好久都没成功,特来此请各位帮忙
程序代码如下:
procedure TForm1.Button1Click(Sender: TObject);
begin
  if edit3.Text='+' then
    edit4.Text:=inttostr(strtoint(edit1.Text)+strtoint(edit2.Text)) ;
  if edit3.Text='-' then
    edit4.Text:=inttostr(strtoint(edit1.Text)-strtoint(edit2.Text));
  if edit3.Text='*' then
    edit4.Text:=inttostr(strtoint(edit1.Text)*strtoint(edit2.Text));
  if edit3.Text='/' then
    edit4.Text:=floattostr((strtoint(edit1.Text))/(strtoint(edit2.Text)));
  end;
end.
请高手能帮我加上异常处理的功能,要求只要输入有一项不正确,就提示;

解决方案 »

  1.   

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      try
       if edit3.Text='+' then
         edit4.Text:=inttostr(strtoint(edit1.Text)+strtoint(edit2.Text)) ;
       if edit3.Text='-' then
         edit4.Text:=inttostr(strtoint(edit1.Text)-strtoint(edit2.Text));
       if edit3.Text='*' then
         edit4.Text:=inttostr(strtoint(edit1.Text)*strtoint(edit2.Text));
       if edit3.Text='/' then
         edit4.Text:=floattostr((strtoint(edit1.Text))/(strtoint(edit2.Text)));
      except
        MessageBox(0, '表达式不合法', '运算错误', MB_OK);
      end;
    end.
      

  2.   

    楼上正解
    不过我更喜欢用下面的这种方式:
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      try
       if edit3.Text='+' then
         edit4.Text:=inttostr(strtoint(edit1.Text)+strtoint(edit2.Text)) ;
       if edit3.Text='-' then
         edit4.Text:=inttostr(strtoint(edit1.Text)-strtoint(edit2.Text));
       if edit3.Text='*' then
         edit4.Text:=inttostr(strtoint(edit1.Text)*strtoint(edit2.Text));
       if edit3.Text='/' then
         edit4.Text:=floattostr((strtoint(edit1.Text))/(strtoint(edit2.Text)));
      except
        on E: Exception do
           Application.MessageBox(PChar('计算时发生错误,原因:('+E.Message + ')'), '警告', MB_OK or MB_ICONINFORMATION);
      end;
    end.
      

  3.   

    还是不行,在执行except中的语句之前,先报一个大的错误,再弹出自己定的哪句信息,或者是什么都不执行,为什么呢,楼上两位的方法我都试过了,行不通,还有更好的方法吗??
    on后面是什么异常才合适呢????
      

  4.   

    你不要在 Delphi 中运行,你说的先报的那个错误,是 Delphi 的调试环境报告的。也就是说,不要通过 Delphi 的“Run”命令来执行你的程序。
    而是直接在 Windows 的资源管理器中双击,运行你的程序,并且用二楼、三楼的朋友的try except方法去捕捉。那个错误对话框就不会出现了。
      

  5.   

    直接点编译好的运行,不要点RUN运行就行了
      

  6.   

    在字符串转换为其它数据时,最好使用:带有默认值的转换函数,不会引起异常:
    如StrToIntDef等
    详情请参照手册。