Search code examples
delphiexceptiontfilestream

How to handle exceptions when creating FileStream


I have a function like this, that I would like to refactor

   function Myfunction(sUrl, sFile: String) : Boolean;
    var
      GetData : TFileStream;
    begin
      Result := False;
      //if the line below fails, I get an unhandled exception
      GetData := TFileStream.Create(sFile, fmOpenWrite or fmCreate);
      try        
        try
          IdHTTP.Get(sUrl, GetData);
          Result := (IdHTTP.ResponseCode = 200);
        except
          on E: Exception do begin
            MessageBox(0, PChar(E.message), 'Niðurhala skrá', MB_ICONERROR or MB_OK);
          end;
        end;
      finally
        GetData.Free;
      end;
    end;

    Procedure SomeOtherCode;
     Begin
        //How can I best defend against the unhandled exception above
        //unless the call to the function is packed in a try .. except block
        //the code jumps skips the if statement an goes to next 
        //exception block on the stack
        if MyFunction('http://domain.com/file.html', 'c:\folder\file.html') then
            ShowMessage('Got the file')
         else
            ShowMessage('Error !');
        End
     end;

Question:

Please refer to the comment within the procedure SomeOtherCode above.

Best Regards


Solution

  • Just wrap the code where you want to trap exceptions in a try..except block:

    function MyFunction(...): Boolean;
    var
      Stream: TFileStream;
    begin
      Result := False;
      try
        Stream := TFileStream.Create(...);
        try
          // more code
          Result := ...
        finally
          Stream.Free;
        end;
      except
        // handle exception
      end
    end;