我见过有人说,使用不带参数的catch是一种糟糕的形式,尤其是当catch什么都不做的时候:
StreamReader reader=new StreamReader("myfile.txt");
try
{
int i = 5 / 0;
}
catch // No args, so it will catch any exception
{}
reader.Close();
然而,这被认为是良好的形式:
StreamReader reader=new StreamReader("myfile.txt");
try
{
int i = 5 / 0;
}
finally // Will execute despite any exception
{
reader.Close();
}
据我所知,将清理代码放在finally块和将清理代码放在try. catch块之后的唯一区别是,如果你在try块中有返回语句(在这种情况下,finally中的清理代码将运行,但try. catch块之后的代码将不会运行)。
否则,最后有什么特别的?
finally块仍然会抛出任何引发的异常。最后要做的就是确保在抛出异常之前运行清理代码。
The try..catch with an empty catch will completely consume any exception and hide the fact that it happened. The reader will be closed, but there's no telling if the correct thing happened. What if your intent was to write i to the file? In this case, you won't make it to that part of the code and myfile.txt will be empty. Do all of the downstream methods handle this properly? When you see the empty file, will you be able to correctly guess that it's empty because an exception was thrown? Better to throw the exception and let it be known that you're doing something wrong.
另一个原因是这样做的try. catch是完全错误的。你这样做的意思是,“无论发生什么,我都能处理好。”StackOverflowException呢,你能在那之后清理吗?OutOfMemoryException呢?一般来说,您应该只处理您期望并知道如何处理的异常。
如果你读过c#,你就会明白finally块是为了优化应用程序和防止内存泄漏而设计的。
CLR并不能完全消除泄漏……如果程序无意中保留了对不需要的对象的引用,就会发生内存泄漏
例如,当您打开一个文件或数据库连接时,您的机器将分配内存来处理该事务,除非执行了dispose或close命令,否则该内存将不会被保留。但是如果在事务处理期间发生了错误,则继续执行的命令将被终止,除非它在try..最后. .块。
Catch与finally的不同之处在于,Catch的设计目的是为您提供处理/管理或解释错误的方法。把它想象成一个人告诉你“嘿,我抓住了一些坏人,你想让我对他们做什么?”
而最终的目的是确保你的资源被正确地配置。想想某人,不管有没有坏人,他都会确保你的财产仍然安全。
你应该让他们俩永远合作下去。
例如:
try
{
StreamReader reader=new StreamReader("myfile.txt");
//do other stuff
}
catch(Exception ex){
// Create log, or show notification
generic.Createlog("Error", ex.message);
}
finally // Will execute despite any exception
{
reader.Close();
}