开发者

Avoiding errors at runtime

I have a lot of commands in one procedure and there is this command:

...
Stream:=TFileStream.Create(FileName,fmOpenread);
...

The whole procedure is created to send file from TClientSocket to TServerSocket.

The procedure is launching every 100 milliseconds from Ti开发者_如何学Gomer. Of course, sometimes I have EFCreateError error showing because the file is used.

Everything works well because some data is received. But how to avoid showing this error?


You need to capture the error and handle it. See the code below.

....
try
  Stream:=TFileStream.Create(FileName,fmOpenread); 
except on E: EFCreateError do
  Stream:= nil;
end; {try}
if Stream <> nil then try
  //rest of your procedure
finally  
  Stream.Free; //make sure your stream is freed.
end;

If there's an error here, no message will be shown in runtime, in debug you will see an error, but you can ignore that.
On error the Stream variable will be set to nil.
In the code that follows you can test Stream <> nil or Assigned(Stream) (which is the same) and do stuff with the stream if all is well.


I think I see what you mean...

You do handle the exceptions properly, but you want to avoid the Delphi IDE popup for each and every exception that occurs.

If so, do the following:

  1. Go to Tools -> Debugger Options
  2. Go to the Language Exceptions tab
  3. Add EFCreateError to the list of exceptions to ignore


Why don't you wrap the access to the file in a mutex or a read/write lock? Then you wouldn't need to rely on a brittle approach like this.

It also sounds like you are polling a file as an inter process communication mechanism. Something like a pipe is likely to be much more effective.


Using try ... finally to cleanup and try ... except to swallow the expected exception:

  Stream := nil; // if it is an unitialized local variable, assign nil
  try
    try
      Stream := TFileStream.Create(Filename, fmOpenread);
    except         
      on E: EFCreateError do
      begin
        // exception thrown if the file is in use
        // and may be ignored in this function
      end;
    end;
  finally
    Stream.Free;
  end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜