0

difference between try...catch and try....finally ? in asp.net(C#)

like when i want to catch error like 1/0 then i put code in try block and put exception object in catch block like response.write("ERROR:"+ ex.Message) but advisors told me that it isn't a good practice to put catch always, it absorbs error without notifying ????? ehhhhh ? but it did via ex.Message , so why ? and what does try....finally do ? i know that it is used to release resources but of what use is TRY if exception can't be catched ?

4

3 回答 3

4

尝试/捕捉/最终:

try
{
    // open some file or connection
    // do some work that could cause exception
}
catch(MyException ex)
{
   // do some exception handling: rethrow with a message, log the error, etc...
   // it is not a good practice to just catch and do nothing (swallow the exception)
}
finally
{
    // do some cleanup to close file/connection
    // guaranteed to run even if an exception happened in try block
    // if there was no finally, and exception happened before cleanup in your try block, file could stay open.
}

尝试/最后:

try
{
    // open some file/connection
    // do some work, where you're not expecting an exception
    // or, you don't want to handle the exception here, rather just let it go to the caller, so no need for a catch
}
finally
{
    // do cleanup, guaranteed to go in this finally block
}
于 2013-10-29T23:16:42.660 回答
2

确保执行 finally 块中包含的所有内容,并且至少在这两种具体情况下可能有用:

  • 有时你决定return在你的 try 块中间调用并返回给调用者:finally简化这里释放资源的过程,你不必编写一些特定的代码来直接进入你的方法的末尾。
  • 有时您想让异常上升(通过不捕获它)并且可能在更高级别被捕获(例如,因为它不是正确处理它的合适位置)。再次finally确保您的资源被释放并且异常继续其路径。

也许您可以将finally其视为一种工具,帮助开发人员以更少的努力完成他们不得不做的事情。另一方面,catch专门处理错误。

这两个关键字都专用于流量控制,但它们的用途不同,它们可以单独使用(而且经常是!)。这取决于您的需求。

于 2013-10-29T23:22:19.803 回答
1

不管有没有异常,finally 总是被执行。如果您想绝对确定某些东西已清理干净,这可能会很方便。 示例

void ReadFile(int index)
{
    // To run this code, substitute a valid path from your local machine 
    string path = @"c:\users\public\test.txt";
    System.IO.StreamReader file = new System.IO.StreamReader(path);
    char[] buffer = new char[10];
    try
    {
        file.ReadBlock(buffer, index, buffer.Length);
    }
    catch (System.IO.IOException e)
    {
        Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
    }

    finally
    {
        if (file != null)
        {
            file.Close();
        }
    }
    // Do something with buffer...
}

如果您没有 finally ,那么如果发生错误,文件可能无法正确关闭。无论是否发生错误,您都希望在完成后关闭文件。

考虑替代方案:

void ReadFile(int index)
{
    // To run this code, substitute a valid path from your local machine 
    string path = @"c:\users\public\test.txt";
    System.IO.StreamReader file = new System.IO.StreamReader(path);
    char[] buffer = new char[10];
    try
    {
        file.ReadBlock(buffer, index, buffer.Length);
        file.Close();
    }
    catch (System.IO.IOException e)
    {
        Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
    }
}

如果您ReadBlock在文件上出错,将无法正确关闭。

于 2013-10-29T23:13:13.920 回答