Niels said:
I guess those try-catch blocks are used for cleaning up database connections
or file handles. Thats where I usually use try-catch in Java.
One of the most annoying omissions in C++ is finally. But fortunately it can
be solved in most cases with a destructor, but in some cases you have to
invent a class for that purpose which does not make the code more readable.
Depends what you're used to I think. To me, Resource Acquisition Is
Initialisation (RAII - acquiring resources in a constructor) is normal
because most of my experience is in C++. Having a class that manages
the resource in its constructor and destructor is natural so I've never
found a need for finally. I don't find that the use of resource
handling classes makes code less readable because they are exactly what
I'm expecting (hoping?) to see.
When I see a resource acquired outside a constructor, then I find the
code harder to read, because I have to start looking for all the places
an expection might be thrown. Then I have to look for where (or even
whether) the different exceptions will be caught and see whether the
resource is released correctly. With RAII that whole concern
disappears.
That is true, but beginners seldom write well-written C++-applications.
C# and Java have solved handling memory resources very well, but C++'s
destructors are very nice for handling all other resources.
But again beginners are not likely to clean up resources correctly.
More recently I've used C#. Memory is garbage collected. Other
resources are not. I found this to be an artificial and unnecessary
distinction between memory and all other resources. But again that's
probably because I come from a C++ background where that distinction
doesn't need to exist.
Bottom line. Whatever language you choose, you need to learn it's own
idioms and not try to force in those from another language. If you are
using C++ but you refuse to embrace RAII and try instead to implement
"finally"-like functionality, you'll find C++ resource management much
more frustrating than it needs to be. If you are using C# or Java and
refuse to embrace try-catch-finally I am sure you will find resource
management there more frustrating than it needs to be too.
Gavin Deane