Monday, February 16, 2009

Try-finally block without catch

We use try-finally block without catch when we want our application to guarantee execution of cleanup code (in finally block) when execution of a block of code. If an exception occurs then the code in finally block will be executed before the exception is thrown to outside.

Consider below example:
void MyMethod1()
{
try
{
MyMethod2();
MyMethod3();
}
catch(Exception e)
{
//do something with the exception
}
}

void MyMethod2()
{
try
{
//perform actions that need cleaning up
}
finally
{
//clean up
}
}

void MyMethod3()
{
//do something
}
If either MyMethod2 or MyMethod3 throws an exception, it will be caught by MyMethod1. However, the code in MyMethod2 needs to run clean up code, e.g. closing a database connection, before the exception is passed to MyMethod1.

Wednesday, February 11, 2009

Instance versus Class variables/methods

1. Instance methods can access instance variables and instance methods directly.
2. Instance methods can access class variables and class methods directly.
3. Class methods can access class variables and class methods directly.
4. Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to