Why is try {…} finally {…} good; try {…} catch{} bad?

后端 未结 20 2387
执笔经年
执笔经年 2020-11-28 01:30

I have seen people say that it is bad form to use catch with no arguments, especially if that catch doesn\'t do anything:

StreamReader reader=new  StreamRead         


        
20条回答
  •  悲&欢浪女
    2020-11-28 01:57

    If you'll read C# for programmers you will understand, that the finally block was design to optimize an application and prevent memory leak.

    The CLR does not completely eliminate leaks... memory leaks can occur if program inadvertently keep references to unwanted objects

    For example when you open a file or database connection, your machine will allocate memory to cater that transaction, and that memory will be kept not unless the disposed or close command was executed. but if during transaction, an error was occurred, the proceeding command will be terminated not unless it was inside the try.. finally.. block.

    catch was different from finally in the sense that, catch was design to give you way to handle/manage or interpret the error it self. Think of it as person who tells you "hey i caught some bad guys, what do you want me to do to them?" while finally was designed to make sure that your resources was properly placed. Think of it of someone that whether or not there is some bad guys he will make sure that your property was still safe.

    And you should allow those two to work together for good.

    for example:

    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();
    }
    

提交回复
热议问题