Tuesday, October 21, 2008

.net try catch finally

Yesterday, dechu said he once read my blog. I then realize I have a blog... Almost forgot this place. Today I am going to talk about try, catch, finally.
Few years ago, I used try catch to avoid unexcepted error, and always put everything in a big try block. Catch the error, maybe print it out and that's it. This is a really bad practice.
I started to look at other people's code, and learned to do some clean up in finally block, however, this is still not enough. Now I started to use multiple level try & catch, in the lower level,
trying to rollover previous actions like a sql transaction in catch block, and then throw new exception to upper level code. This improve the error handling abilities and allow code structure to be easily handled. The disadvantage is the performance issue of throwing exceptions.
But considering we are not using exceptions mechanism to achieve certain result, the time consuming exception won't eat up resources in the normal run.

First look at this code below:


/ try-catch-finally
using System;public class TRYCATCHFINALLY
{
public static void Main ()
{
try
{
Console.WriteLine("Executing the try statement.");
try
{
DoSomething();
}
catch (System.Exception sex)
{
throw new SomethingFailedException();
}
Console.WriteLine("Now something done, try other things now.");
try
{
DoOtherthing();
}
catch (System.Exception oex)
{
throw new OtherthingFailedException();
}
Console.WriteLine("Executing the try all done.");
}
catch (SomethingFailedException sfe)
{
Console.WriteLine("{0} Caught exception #1.", e);
}
catch (OtherthingFailedException ofe)
{
Console.WriteLine("{0} Caught exception #1.", e);
}
finally
{
Console.WriteLine("Executing finally block. Clean up
everything.");
}
}
private void DoSomething()
{
try
{
//Hello 6sb
}
catch (System.Exception e)
{
//Rollover
throw new Exception WhateverException();
}
finally
{
// clean up
}
}

private void DoOtherthing()
{
try
{
//lv 6sb
}
catch (System.Exception e)
{
//Rollover
throw New Exception WhateverException();
}
finally
{
// clean up
}
}
}



1 comment:

alisha said...

Yesterday, Dechu mentioned he once read my blog, and it made me realize I had almost forgotten about it. I want to share my experience with error handling in programming. A few years ago, I would just try to run everything and print errors when they occurred, which was not effective. Now, I make sure to carefully manage previous actions, like rolling back SQL transactions when something goes wrong, and then pass the error up to be handled at a higher level. This improves code reliability and keeps it organized. While handling errors this way can affect performance slightly, it rarely impacts normal execution. Guidance from a Research Proposal Writer has helped me structure my approach efficiently.