//我已经在Catch块中编写了代码
try {
} catch(Excepetion ex) {
// I have written code here If Exception Occurs then how to handle it.
}
最好的方法是为不同层次的应用程序开发自己的异常,并使用内部异常抛出它。它将在你的应用程序的下一层处理。如果你认为,在catch块中可以得到一个新的异常,只需重新抛出此异常而不进行处理。
让我们想象一下,你有两个层次:业务逻辑层(BLL)和数据访问层(DAL),在DAL的catch块中有一个异常。
DAL:
try
{
}
catch(Excepetion ex)
{
// if you don't know how should you handle this exception
// you should throw your own exception and include ex like inner exception.
throw new MyDALException(ex);
}
BLL:
try
{
// trying to use DAL
}
catch(MyDALException ex)
{
// handling
}
catch(Exception ex)
{
throw new MyBLLException(ex);
}
try
{
// Some code here
}
catch (Exception ex)
{
try
{
// Some more code
}
catch (Exception ex)
{
}
}
对于在catch
块中可能会抛出异常的代码行,需添加额外的显式的try..catch块。此外,考虑添加finally
块,以确保所有行都能得到执行。同样的问题也可能出现在finally
块中。因此,如果您的代码可能会在finally
块中抛出异常,也可以在那里添加try..catch块。
try
{
}
catch (Exception ex)
{
try
{
// code that is supposed to throw an exception
}
catch (Exception ex1)
{
}
// code that is not supposed to throw an exception
}
finally
{
try
{
// code that is supposed to throw an exception
}
catch (Exception ex1)
{
}
// code that is not supposed to throw an exception
}
我的朋友Atul...如果你在catch块中编写try..catch,并且如果内部的try..catch再次发生异常,同样的问题将再次引起。 为了解决这个问题,您可以在Global.asax中处理应用程序级事件中的这些错误。
请查看以下链接。
http://msdn.microsoft.com/en-us/library/24395wz3%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/fwzzh56s%28v=vs.80%29.aspx
如果这对你有用,请告诉我.. :)
catch
中不会抛出异常,或者最起码将其封装为另一个方法。多个嵌套的try/catch/finally
代码块是一种代码味道--至少对我来说是这样的 :)。 - Jduv