From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=-1.9 required=5.0 tests=BAYES_00 autolearn=ham autolearn_force=no version=3.4.4 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 103376,d8a4797a79f9c90f X-Google-Attributes: gid103376,public X-Google-ArrivalTime: 2003-05-26 09:31:55 PST Path: archiver1.google.com!news1.google.com!newsfeed.stanford.edu!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!small1.nntp.aus1.giganews.com!border3.nntp.aus1.giganews.com!nntp.giganews.com!wn14feed!worldnet.att.net!204.127.198.203!attbi_feed3!attbi.com!rwcrnsc52.ops.asp.att.net.POSTED!not-for-mail From: "Steve" Newsgroups: comp.lang.ada References: Subject: Re: I/O - exception handling X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 6.00.2800.1106 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1106 Message-ID: <_jrAa.4696$_t5.1827@rwcrnsc52.ops.asp.att.net> NNTP-Posting-Host: 12.211.13.75 X-Complaints-To: abuse@attbi.com X-Trace: rwcrnsc52.ops.asp.att.net 1053966714 12.211.13.75 (Mon, 26 May 2003 16:31:54 GMT) NNTP-Posting-Date: Mon, 26 May 2003 16:31:54 GMT Organization: AT&T Broadband Date: Mon, 26 May 2003 16:31:54 GMT Xref: archiver1.google.com comp.lang.ada:37797 Date: 2003-05-26T16:31:54+00:00 List-Id: Here's an approach that only uses close once, but it isn't pretty either. begin begin begin Open (File, Name => "test.txt", Mode => In_File); exception when others => null; -- report exception opening file ??? return; end; Get_Line (File, S1); Get_Line (File, S2); exception when others => null; -- report exception??? end; Close (File); exception when others => null; -- report exception ??? end Read_Something; Steve (The Duck) "Sergey Koshcheyev" wrote in message news:bat3ee$2ec$1@ns.felk.cvut.cz... > Hi, > > I have this problem: I have a simple piece of code opening a file, reading a > few lines, then closing it. Now, I want this piece of code to be "safe", > i.e. not to leak any resources (the open file) in case of errors and not to > propagate any exceptions. What is the best style to write this code? > > Currently, I have something like (not compiled): > > procedure Read_Something (...) is > use Ada.Text_IO; > use Ada.Strings.Unbounded; > use Ada.Strings.Unbounded.Text_IO; > -- GNAT-specific package, I believe > > File : File_Type; > S1, S2 : Unbounded_String; > > begin > Open (File, Name => "test.txt", Mode => In_File); > Get_Line (File, S1); > Get_Line (File, S2); > Close (File); > > exception > when others => > if Is_Open (File) then > begin > Close (File); > exception > -- Close can raise exceptions too! > when others => null; > end; > end if; > end Read_Something; > > However, this looks ugly to me, since I have to close the file in two > places, and also guard for exceptions while handling exceptions. Is there a > better solution or is this sort of thing OK in the Ada way? > > Sergey. > >