就像我想要捕获像1/0这样的错误然后我把代码放在try块中并将异常对象放在catch块中就像response.write(“ERROR:”+ ex.Message)但是顾问告诉我它不是'一个很好的做法总是把捕获,它吸收错误而不通知?????呃?但它是通过ex.Message完成的,为什么呢? 什么尝试....终于做到了?我知道它用于释放资源,但是如果无法获取异常,那么TRY的用途是什么?
答案 0 :(得分: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
}
答案 1 :(得分:2)
确保执行封锁在finally块中的Eveything,它至少在这两个具体案例中有用:
return
并返回调用者:finally
简化了在此处释放ressource的过程,您不必编写一些特定的代码直接进入方法的最后。finally
确保您的资源被释放,异常继续其路径。也许你可以看到finally
作为一种工具,帮助开发人员以更少的努力完成他们必须做的事情。另一方面,catch
致力于处理错误。
这两个关键字都专用于流量控制,但它们没有相同的用途,它们可以互相使用(通常是!)。这取决于你的需求。
答案 2 :(得分:1)
最后总是执行是否存在异常。如果您想要绝对确定清理了某些东西,这可能很方便。 Example:
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...
}
如果你没有最终版本,那么如果发生错误,文件可能无法正确关闭。无论是否发生错误,您都希望在完成后关闭文件。
考虑替代方案:
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
上输入错误,则文件将无法正常关闭。