From: Nit Khair Date: 2008-10-06T01:31:03+09:00 Subject: Re: "ensure" hiding actual error Robert Klemme wrote: > On 02.10.2008 14:48, Nit Khair wrote: >>>> } >>> This is common in Java, but it is incorrect. >>> >>> What happens if init_resource() throws an exception? >> >> Oops I forgot to mention that in finally {} one would check for resource >> not being nil. Corrected above. > > The pattern is still broken - or put it differently: overly complex. > This is easier and as safe - and you can make the resource final and > avoid accidental reassignment: > > final Resource res = initResource(); > try { > res.use(); > res.use(); > res.use(); > res.use(); > } > finally { > res.cleanup(); > } > > Cheers > > robert Actually, I have left Java 4 years back. However, that being my last programming language i still tend to thing in that way. IIRC, the above pattern is used commonly because most, if not all, books gave it in their samples. Take file opening or a database connection, for example. Since it can throw a file not found exception, or a database connection etc exception, the JDBC tutorials will recommend: declare db variable try { db = create_dbconnection(...) db.use } catch (ex){} finally { cleanup code } Anyway, I'd like to ask, if I use your suggested pattern of opening a file or creating a resource before a begin/rescue/ensure block, would that not mean i am not trapping failures from that. (I am just unused to thinking this way! Could you point me to some code that illustrates this. Also, is there a quick way to know what exceptions a method can throw ? Or is that not relevant ? -- Posted via http://www.ruby-forum.com/.