“If an exception is raised but not handled in the finally clause, that exception is propagated out of the try...finally statement, and any exception already raised in the try clause is lost. The finally clause should therefore handle all locally raised exceptions, so as not to disturb propagation of other exceptions.”以上一段文字摘自Delphi 7 的帮助文档,从中,我得到了一个信息,“在finally 块中要处理异常”,但是Finally 块不是负责释放资源等工作的吗?

解决方案 »

  1.   

    tryfinally
    //程序不管出现异常还是未出现异常都都执行这里的代码
    end;
      

  2.   

    还有个
    tryexecpt
    //出错了才执行的代码
    end;
    所以当我们手动实例化对象后,程序执行可能出现异常的代码时,我们要在程序出现异常时进行对象释放工作举个例子:
    try
      Screen.Cursor := crHourGlass  ;
      ShowMessage(inttostr(strtoint('dddddd')));
    finally
      Screen.Cursor := crDefault;//看看这句加与不加的区别
    end;这个例子虽然不好,但我认为也能说明一些问题了
      

  3.   

    这个我知道,我不懂的地方是,finally 中是否要处理异常。
      

  4.   


    不用,把处理异常的放在except就行,而一些必需处理的代碼就放在finally中
      

  5.   

    后面的这个例子其实也就是在处理异常了呀,Screen.Cursor := crDefault;变回手形,如果没这句处理的话,直接这样
    Screen.Cursor := crHourGlass ;
    ShowMessage(inttostr(strtoint('dddddd')));
    Screen.Cursor := crDefault;
    那程序出错了后始终是双前头了
      

  6.   

    一般这样:try
      try  except
        //这里处理异常
      end;
    finally
      //这里释放资源
    end;也有这样的:
    try
      try  finally  end;
    exceptend;
    看情况吧,异常处理只有通过自己实际运用才能了解一些,不过即使用了,我也还是有一些迷胡
      

  7.   

    但是帮助文档中却指明了在finally 中处理异常,“The finally clause should therefore handle all locally raised exceptions”,难道是我理解错了?
      

  8.   

    谢谢楼上的几位回答,可能我没表述清楚,我知道异常的常用方法,但是今天偶然读到帮助文档时,犯迷糊了,“The finally clause should therefore handle all locally raised exceptions”这名话是摘自帮助文档中的,它想表达的意思是什么?
      

  9.   

    try
      发生异常A
    finally
      发生异常B
    end在运行的时候,异常B会抛出来,而异常A不会抛,"丢失"了!
    The finally clause should therefore handle all locally raised exceptions
    这句话是说要处理异常B,比如用try..except把异常B包起来,这样异常A就会抛出来了!例子:
    procedure TForm1.FormCreate(Sender: TObject);
    var
      L: TList;
    begin
      L := TList.Create;
      try
        L.Items[0] := Self;//异常A,下标越界
      finally
        L.Free;
        Tag := 0;
    //    try
          Tag := 1 div Tag;//异常B,被0除。如果它没被try..except包起来的话,异常A就不会报,而异常B会!
    //    except
    //
    //    end;
      end;
    end;
      

  10.   

    对这段话,我的理解正好跟 lz 反一下。
    是说如果 finally 段有异常的话,会替换掉(如果有的话)try 里出现的异常。
    不是要在 finally 处理异常,是要保证 finally 里不会再有异常的代码。