Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Try ... except ... end;

Status
Not open for further replies.

tjcusick

Programmer
Dec 26, 2006
134
US
I am using delphi 7.
What I am doing in this code is reading a txt file that has 4 lines of information. With those 4 lines of information i am then creating another text file (with the extension of .index). I need to make sure that the txt file exists before attempting to create the index file, but using the try...except...end; does not work when i have two in a row. it always creates the index file without all the information. How can i go about using the error handling of try except but have the second one conditional on the first?
Code:
procedure TForm1.readtxtfile(fn:String);

  procedure GetValue(var value:string);
  var
    position : integer;
  begin
    if AnsiContainsText(value, '=') then { Does the line contain an equals sign }
    begin
      position:=AnsiPos('=', value);     { Find the location of the equals sign }
      value:=TRIM(MidStr(value,position+1,length(value)));  { Get Value after the equals sign }
    end;
  end;

var
  mytxt, myindex: TextFile;
  AppName, DateSub, Company, PolType : String;
  sLOB : String;
  i:integer;
begin
//  if fn <> '' then begin
    try
      { Reading the Text File }
      AssignFile(mytxt, srcDir+'\'+fn+'.txt');  { Open Text File }
      FileMode := fmOpenRead;        { Open the file in read only mode }
      Reset(mytxt);                  { Open file for reading }
      Readln(mytxt, AppName);        { Read Applicant's Name Line }
      GetValue(AppName);             { Get Just Applicant's Name }
      Readln(mytxt, DateSub);        { Read Date Submitted Line }
      GetValue(DateSub);             { Get Just Date Submitted }
      Readln(mytxt, Company);        { Read Company Line }
      GetValue(Company);             { Get Just Company }
      Readln(mytxt, PolType);        { Read Policy Type Line }
      GetValue(PolType);             { Get Just LOB }
      cdsFilesAppName.AsString := AppName;  { Add Applicant's Name to Client Dataset Table }
      cdsFilesDateSub.AsString := DateSub;  { Add Date Submitted to Client Dataset Table }
      cdsFilesCompany.AsString := Company;  { Add Company to Client Dataset Table }
      cdsFilesPolType.AsString := PolType;  { Add Policy Type to Client Dataset Table }
      CloseFile(mytxt);              { Close file }
    except
      { Email because there is no corresponding txt file }
      myMsg.Add('There is no corresponding txt file for' + fn + '.pdf');
      SendEmail(strIniFile, myMsg);
    end;

    try
      { Writing/Building the index file }
      AssignFile(myindex, dstDir+'\'+fn+'.index');  { Create Index File }
      Rewrite(myindex);                { Open file for writing }
      Write(myindex,Item1+Sepr);       { Write Values from ini file }
      Write(myindex,Item2+Sepr);       { Write Values from ini file }
      Write(myindex,Item3+Sepr);       { Write Values from ini file }
      Write(myindex,Item4+Sepr);       { Write Values from ini file }
      Write(myindex,Item5+Sepr);       { Write Values from ini file }
      Write(myindex,dstDir+'\'+fn+'.pdf'+Sepr);   { Write Destination Directory and PDF file name }
      Write(myindex,Item7+Sepr);       { Write Values from ini file }
      for i := 1 to CLHM do            { Determine if the Policy Type is Commercial or Personal }
      begin
        if PolType = CLLOB[i] then begin   { Compare the Policy type to the list of Commercial LOBs retrieved from the ini file }
          sLOB := 'CL';
          break;
         end
        else if PolType = PLLOB[i] then begin  { Compare the Policy type to the list of Personal LOBs retrieved from the ini file }
          sLOB := 'PL';
          break;
         end;
      end;
      Write(myindex,sLOB+Sepr);        { Write CL or PL }
      Write(myindex,AppName+Sepr);     { Write Applicant's name }
      Write(myindex,PolType+Sepr);     { Write Policy type }
      Write(myindex,Company+Sepr);     { Write Company }
      Write(myindex,Item12+Sepr);      { Write Values from ini file }
      Write(myindex,Item13+Sepr);      { Write Values from ini file }
      Write(myindex,Item14+Sepr);      { Write Values from ini file }
      Write(myindex,Item15+Sepr);      { Write Values from ini file }
      Write(myindex,Item16+Sepr);      { Write Values from ini file }
      Write(myindex,DateSub+Sepr);     { Write Date Submitted }
      Write(myindex,Item18);           { Write Values from ini file }
      CloseFile(myindex);              { Close file }
    except
      { Email because unable to create index file }
      myMsg.Add('Unable to create index file');
      SendEmail(strIniFile, myMsg);
    end;
//  end;
end;       {}
 
ditch the try except and use the FileExists(Filename) function

something like:

Code:
 if FileExists(srcDir+'\'+fn+'.txt') then
    begin
      { Reading the Text File }
      AssignFile(mytxt, srcDir+'\'+fn+'.txt');  { Open Text File }
      FileMode := fmOpenRead;        { Open the file in read only mode }
      Reset(mytxt);                  { Open file for reading }
      Readln(mytxt, AppName);        { Read Applicant's Name Line }
      GetValue(AppName);             { Get Just Applicant's Name }
      Readln(mytxt, DateSub);        { Read Date Submitted Line }
      GetValue(DateSub);             { Get Just Date Submitted }
      Readln(mytxt, Company);        { Read Company Line }
      GetValue(Company);             { Get Just Company }
      Readln(mytxt, PolType);        { Read Policy Type Line }
      GetValue(PolType);             { Get Just LOB }
      cdsFilesAppName.AsString := AppName;  { Add Applicant's Name to Client Dataset Table }
      cdsFilesDateSub.AsString := DateSub;  { Add Date Submitted to Client Dataset Table }
      cdsFilesCompany.AsString := Company;  { Add Company to Client Dataset Table }
      cdsFilesPolType.AsString := PolType;  { Add Policy Type to Client Dataset Table }
      CloseFile(mytxt);              { Close file }
    end
  else SendEmail(...)

/Daddy

-----------------------------------------------------
What You See Is What You Get
Never underestimate tha powah of tha google!
 
You can 'nest' the try/except structures put the whole of the second structure just before the except of the first.

But in itself try/except wont wait until the file is created if there are no errors.

Code:
 CloseFile(mytxt);              { Close file }
Does not guarantee that the file will be closed when the following lines execute.
A sort delay followed by an if fileexists(fn) might be in order.

Also it might be more correct to use a try/finally to make sure the files get closed. You can nest these as well.





Steve: N.M.N.F.
If something is popular, it must be wrong: Mark Twain
 
How does this look for better error handling?
Code:
[navy][i]// for automatic syntax highlighting see faq102-6487 
[/i][/navy][b]procedure[/b] TForm1.readtxtfile(fn:String);

  [b]procedure[/b] GetValue([b]var[/b] value:string);
  [b]var[/b]
    position : integer;
  [b]begin[/b]
    [b]if[/b] AnsiContainsText(value, [teal]'='[/teal]) [b]then[/b] [navy][i]{ Does the line contain an equals sign }[/i][/navy]
    [b]begin[/b]
      position:=AnsiPos([teal]'='[/teal], value);     [navy][i]{ Find the location of the equals sign }[/i][/navy]
      value:=TRIM(MidStr(value,position+[purple]1[/purple],length(value)));  [navy][i]{ Get Value after the equals sign }[/i][/navy]
    [b]end[/b];
  [b]end[/b];

[b]var[/b]
  mytxt, myindex: TextFile;
  AppName, DateSub, Company, PolType : String;
  sLOB : String;
  i:integer;
[b]begin[/b]
[navy][i]//  if fn <> '' then begin
[/i][/navy]    [b]if[/b] FileExists(srcDir+[teal]'\'[/teal]+fn+[teal]'.txt'[/teal]) [b]then[/b]
      [b]begin[/b]
        [navy][i]{ Reading the Text File }[/i][/navy]
        AssignFile(mytxt, srcDir+[teal]'\'[/teal]+fn+[teal]'.txt'[/teal]);  [navy][i]{ Open Text File }[/i][/navy]
        FileMode := fmOpenRead;        [navy][i]{ Open the file in read only mode }[/i][/navy]
        Reset(mytxt);                  [navy][i]{ Open file for reading }[/i][/navy]
        Readln(mytxt, AppName);        [navy][i]{ Read Applicant's Name Line }[/i][/navy]
        GetValue(AppName);             [navy][i]{ Get Just Applicant's Name }[/i][/navy]
        Readln(mytxt, DateSub);        [navy][i]{ Read Date Submitted Line }[/i][/navy]
        GetValue(DateSub);             [navy][i]{ Get Just Date Submitted }[/i][/navy]
        Readln(mytxt, Company);        [navy][i]{ Read Company Line }[/i][/navy]
        GetValue(Company);             [navy][i]{ Get Just Company }[/i][/navy]
        Readln(mytxt, PolType);        [navy][i]{ Read Policy Type Line }[/i][/navy]
        GetValue(PolType);             [navy][i]{ Get Just LOB }[/i][/navy]
        cdsFilesAppName.AsString := AppName;  [navy][i]{ Add Applicant's Name to Client Dataset Table }[/i][/navy]
        cdsFilesDateSub.AsString := DateSub;  [navy][i]{ Add Date Submitted to Client Dataset Table }[/i][/navy]
        cdsFilesCompany.AsString := Company;  [navy][i]{ Add Company to Client Dataset Table }[/i][/navy]
        cdsFilesPolType.AsString := PolType;  [navy][i]{ Add Policy Type to Client Dataset Table }[/i][/navy]
        CloseFile(mytxt);              [navy][i]{ Close file }[/i][/navy]

        [b]try[/b]
          [navy][i]{ Writing/Building the index file }[/i][/navy]
          AssignFile(myindex, dstDir+[teal]'\'[/teal]+fn+[teal]'.index'[/teal]);  [navy][i]{ Create Index File }[/i][/navy]
          Rewrite(myindex);                [navy][i]{ Open file for writing }[/i][/navy]
          Write(myindex,Item1+Sepr);       [navy][i]{ Write Values from ini file }[/i][/navy]
          Write(myindex,Item2+Sepr);       [navy][i]{ Write Values from ini file }[/i][/navy]
          Write(myindex,Item3+Sepr);       [navy][i]{ Write Values from ini file }[/i][/navy]
          Write(myindex,Item4+Sepr);       [navy][i]{ Write Values from ini file }[/i][/navy]
          Write(myindex,Item5+Sepr);       [navy][i]{ Write Values from ini file }[/i][/navy]
          Write(myindex,dstDir+[teal]'\'[/teal]+fn+[teal]'.pdf'[/teal]+Sepr);   [navy][i]{ Write Destination Directory and PDF file name }[/i][/navy]
          Write(myindex,Item7+Sepr);       [navy][i]{ Write Values from ini file }[/i][/navy]
          [b]for[/b] i := [purple]1[/purple] [b]to[/b] CLHM [b]do[/b]            [navy][i]{ Determine if the Policy Type is Commercial or Personal }[/i][/navy]
          [b]begin[/b]
            [b]if[/b] PolType = CLLOB[i] [b]then[/b] [b]begin[/b]   [navy][i]{ Compare the Policy type to the list of Commercial LOBs retrieved from the ini file }[/i][/navy]
              sLOB := [teal]'CL'[/teal];
              break;
             [b]end[/b]
            [b]else[/b] [b]if[/b] PolType = PLLOB[i] [b]then[/b] [b]begin[/b]  [navy][i]{ Compare the Policy type to the list of Personal LOBs retrieved from the ini file }[/i][/navy]
              sLOB := [teal]'PL'[/teal];
              break;
             [b]end[/b];
          [b]end[/b];
          Write(myindex,sLOB+Sepr);        [navy][i]{ Write CL or PL }[/i][/navy]
          Write(myindex,AppName+Sepr);     [navy][i]{ Write Applicant's name }[/i][/navy]
          Write(myindex,PolType+Sepr);     [navy][i]{ Write Policy type }[/i][/navy]
          Write(myindex,Company+Sepr);     [navy][i]{ Write Company }[/i][/navy]
          Write(myindex,Item12+Sepr);      [navy][i]{ Write Values from ini file }[/i][/navy]
          Write(myindex,Item13+Sepr);      [navy][i]{ Write Values from ini file }[/i][/navy]
          Write(myindex,Item14+Sepr);      [navy][i]{ Write Values from ini file }[/i][/navy]
          Write(myindex,Item15+Sepr);      [navy][i]{ Write Values from ini file }[/i][/navy]
          Write(myindex,Item16+Sepr);      [navy][i]{ Write Values from ini file }[/i][/navy]
          Write(myindex,DateSub+Sepr);     [navy][i]{ Write Date Submitted }[/i][/navy]
          Write(myindex,Item18);           [navy][i]{ Write Values from ini file }[/i][/navy]
          CloseFile(myindex);              [navy][i]{ Close file }[/i][/navy]
        [b]except[/b]
          [navy][i]{ Email because unable to create index file }[/i][/navy]
          myMsg.Add([teal]'Unable to create index file'[/teal]);
          SendEmail(myMsg);
          myMsg.Clear;
        [b]end[/b];
      [b]end[/b]
    [b]else[/b]
      [b]begin[/b]
        [navy][i]{ Email because there is no corresponding txt file }[/i][/navy]
        myMsg.Add([teal]'There is no corresponding txt file for'[/teal] + fn + [teal]'.pdf'[/teal]);
        SendEmail(myMsg);
        myMsg.Clear;
      [b]end[/b];
 
You are still using try/except if something goes wrong with your write to file the try/except will quit out at the point of the error and do the except part missing your Closefile() statement.
This will leave the file in an unclosed state.

Some I/O errors don't raise an exception so it wont trap those anyway.

Use try/finally then if then whatever happens in the try part the finally will execute ensuring the file is closed.

You can use IOResult to get IO type errors..
I have used both methods...

$I- turns off the IO Exception checking.
Code:
    {$I-}
                      mkdir(Dest);
                      t := IOResult;
                      {$I+}
                      if t > 0 then
                         begin
                            case T of
                            2: AddtoLog('Item ' + inttostr(a + 1) +' :IO Error '+ inttostr(T) + ': Path Not found ' + Dest);
                            3: AddtoLog('Item ' + inttostr(a + 1) +' :IO Error '+ inttostr(T) + ': File Not found ' + Dest);
                           19: AddtoLog('Item ' + inttostr(a + 1) +' :IO Error '+ inttostr(T) + ' The drive is write protected')
                            else
                               AddtoLog('Item ' + inttostr(a + 1) +' :IO Error ' + inttostr(T));
                            end;
If it is on an ElnOutError should be generated on IO errors
e.g.


Code:
    if directoryexists(Destfolder.Text) then
                                    try
                                       CopyFile(trim(updatelocation + R.Strings[a]), addslash(DestFolder.Text) + getname)
                                    except
                                        on E: EInOutError do
                                        case E.ErrorCode of
                                        32:  showmessage('File Error: The target file may already be open');
                                        112: showmessage('File Error: Disk Full');
                                        end;
                                    end
                                 else
                                    begin
                                       AddtoLog('Copy failed; Can''t find destination Folder '+ DestFolder.Text);
                                       if LocalSel.ItemIndex = 1 then
                                          begin
                                             DoLocalCopy(R.Strings[a]);
                                          end;
                                    end



Steve: N.M.N.F.
If something is popular, it must be wrong: Mark Twain
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top