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
}
}
}



Wednesday, October 8, 2008

.Net 的优缺点

.Net === 一堆库+虚拟机
.Net + C# === Java + JVM
普遍觉得有以下优点:
1. MS主推
2. 支持多语言
3. .NET的核心虚拟机CLR将c#这种编译出来的CIL中间代码再编译成机器代码,而非jvm的解析,所以运行速度快
4. 安全,内存,异常处理都在虚拟机内得到一定的保证。
5. 跨平台ms没做,支持了一个叫Mono的项目,可以在Linux, Solaris, Mac OS X, BSD, HP-UX下面跑,不过现在也就做到.Net 2.0
 
我自己认为的好处:
1. 写完程序配置起来简单,基本上机器都会在自动跟新的时候装上这个.net runtime envrionment
2. 学起来容易,不管是web application还是desktop software,学了很大一部分能通用
3. VS用起来蛮舒服。
4. 跟sqlserver也结合紧密,甚至可以说跟ms的所有东西都结合紧密。
5. 开速开发GUI的首选吧。
6. 开发web service嗷嗷简单,客户端如果也用.net,API这块省力。
 
缺点:
1. 代码保护不容易,跟java似的。。
2. 更新太快,丫的3.0还好,3.5就是一个更新的平台,引进一堆没听过的东西。。现在已经出4.0了。
3. 跟人说会这么好像很没面子,不如gs的python来的野性。。。哈哈
4. 有些功能没有,要调用windows library里面的函数了,MFC能干的丫的managed code不一定能干,只能走unsafe code的路子,但是前面的优势就没那么明显了。