Re: Why C++ Is Not ???Back???
On Wednesday, December 5, 2012 7:36:26 PM UTC+1, Luca Risolia wrote:
On 05/12/2012 10:05, g.............@gmail.com wrote:
On Wednesday, December 5, 2012 4:11:10 AM UTC+1, Luca Risolia wrote:
if (r != null) // cannot omit != null, no convertion op.
You should put construction of the reader outside the try, and you
then have no "if" in the catch below. I see people do this all the
time, why?
Because sometimes you want the finally block to get executed even if the
constructor throws.
If you want that, then you can do:
try
{
TYPE instance = new TYPE(...);
try
{
use(instance);
}
finally
{
instance.close(); // etc.
}
}
finally
{
// Your "additional" code here.
}
True, this is longer in pure lines of code, but IMO
the intention is clearer than with an if.
Furthermore, if you put the statement outside any
try, then the method must specify all the checked exceptions that the
constructor can throw.
Well, for that, same as above, really: you wrap the whole of the function i=
nto a try-catch and rethrow your exception wrapping the original. I would f=
urther argue that you have to do that anyhow. Say that the code is (conside=
ring the "standard" Java "wrap/rethrow" approach to checked exceptions):
void f() throws myException
{
try
{
TYPE instance = new TYPE(...);
use(instance);
instance.close();
}
catch(Exception e)
{
try
{
if (instance != null) instance.close();
}
catch(Exception e)
{
throw new myException(msg, e);
}
throw new myException(msg, e);
}
}
with what I propose, you get
void f() throws myException
{
try
{
TYPE instance = new TYPE(...);
try
{
use(instance);
}
finally
{
instance.close();
}
}
catch(Exception e)
{
throw new myException(msg, e);
}
}
which is not much different. In fact, there's less duplicated code in the l=
atter (only one call to instance.close, only one "rethrow").
I am not sure why the Java exception
specification is supposed to help the programmer write safer programs..
Me neither. I think, because it's cumbersome, people dodge the question in =
various ways (e.g. catch(Exception) {/*swallow*/ }) and get poor end result=
s anyhow ;-).
Goran.