what is the difference between TRY…CATCH and TRY…Finally?
本问题已经有最佳答案,请猛点这里访问。
试…抓…试…最后?在ASP.NET中(C语言)
就像当我想捕捉1/0这样的错误时,我把代码放在try块中,把异常对象放在catch块中,比如response.write("错误:"+ex.message),但是advisors告诉我把catch放在catch块中并不是一个好的实践,它会在不通知的情况下吸收错误???????嗯?但它是通过前信息实现的,那为什么呢?什么是尝试…最后做?我知道它是用来释放资源的,但是如果不能捕获异常,它有什么用处呢?
尝试/捕获/最终:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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. } |
尝试/最后:
1 2 3 4 5 6 7 8 9 10 | 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 } |
最后一个块中包含的所有内容都将被确保执行,并且至少在这两种具体情况下是有用的:
- 有时,您决定在try块的中间调用
return 并返回到调用者:finally 简化释放资源的过程,您不必编写一些特定的代码来直接转到方法的末尾。 - 有时候你想让一个异常上升(因为没有捕捉到它),可能会被更高级别的捕获(因为它不是适当的处理它的地方,例如)。同样,
finally 确保您的资源被释放,异常继续其路径。
也许您可以将
这两个关键字都是专用于流控制的,但是它们没有相同的用途,它们可以彼此单独使用(通常是!)这取决于你的需要。
无论是否有异常,都始终执行finally。如果你想确定什么东西被清理干净了,这就很方便了。例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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文件,则在发生错误时可能无法正确关闭文件。无论是否发生错误,都希望在完成后关闭文件。
考虑替代方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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); } } |
如果在