Author Topic: Comments...  (Read 5959 times)

0 Members and 1 Guest are viewing this topic.

Glenn R

  • Guest
Re: Comments...
« Reply #15 on: February 23, 2007, 09:17:52 PM »
Let me expand a little on Tim's explanation.

First off, in C++ and to SOME extent in C#, curly braces {} define a CODE BLOCK, or, more importantly, a SCOPE. In C++/ARX, I would declare a smart pointer (you listening Chuck) deliberately INSIDE a set of curly braces. Why? The reason is simple. Automatic variables on the stack are destroyed immediately upon exit from a CODE BLOCK. Hence, the destructor is immediately called for the smart pointer and it's closed and destroyed - nice and neat.

The closest we have to that in C# is the 'Using' statement. Now, it doesn't necessarily have to have curly braces as it could be one line, as my example above. The important part about it is simialr to the C++ description - upon exiting the using 'block', the variables you are using immediately have their 'Dispose()' method called, essentially cleaning up the resources the object used. Incidentally, a 'using' statement produces IL that is if you had written a try/finally construct.

A try/catch/finally construct IS one block, if you will. You can't have a try without either a catch AND/OR finally clause. Now, the order of the catch clauses is VERY VERY important. As Tim pointed out, the runtime will evaluate each catch clause and immediately execute the one that matches. However, you have to remember one thing - ALL exception classes ultimately inherit from System.Exception. So, as all other exceptions DERIVE/INHERIT from System.Exception, the catch clauses MUST go from MOST SPECIFIC to LEAST SPECIFIC.

An example. Imagine if your code threw an FileNotFoundException and you catch blocks went in this order: System.Exception THEN FileNotFoundException. The FileNotFoundException catch clause would NEVER execute seeing as it derives from System.Exception and it was the first one tried. Inheritance/polymorpphism rules come into play.

The golden rule for catch clauses: MOST to LEAST specific.

Cheers,
Glenn.
« Last Edit: February 23, 2007, 09:22:21 PM by Glenn R »