我正在使用 Try Catch 进行所有与数据库相关的操作。在此事件期间,我使用 Try Catch 甚至是我将参数发送到 ADO.Net 过程而不是实际调用该过程的语句。如果我使用 Try Catch 来监视实际上永远不会发生异常的代码,它会影响应用程序的性能吗?
例。 1)
Try
{
SqlParameter[] spParameters =
{ new SqlParameter("@Batch_ID", SqlDbType.BigInt),
new SqlParameter("@Terminal_ID", SqlDbType.VarChar,8),
new SqlParameter("@MID",SqlDbType.VarChar,15)
spParameters[0].Value = nBatch_ID;
spParameters[1].Value = strTerminal_ID;
spParameters[2].Value = strMID;
objResponse.ResponseValue = MyBlock.ExecuteDataset(strConString,
"Insert_Act_Txn", spParameters);
}
catch(Exception Ex)
{
//logger function to write exception in log file
}
例。 2)
SqlParameter[] spParameters =
{ new SqlParameter("@Batch_ID", SqlDbType.BigInt),
new SqlParameter("@Terminal_ID", SqlDbType.VarChar,8),
new SqlParameter("@MID",SqlDbType.VarChar,15)
spParameters[0].Value = nBatch_ID;
spParameters[1].Value = strTerminal_ID;
spParameters[2].Value = strMID;
Try
{
objResponse.ResponseValue = MyBlock.ExecuteDataset
(strConString, "Insert_Act_Txn", spParameters);
}
catch(Exception Ex)
{
//logger function to write exception in log file
}
在示例中,我正在使用 try catch 语句,我正在为过程创建参数并为其赋值,而运行时异常永远不会发生,而不是调用实际过程,但在 Ex.-2 中,我仅在我使用它时才使用它我实际上是在调用这个程序。
从性能上考虑,哪种方式好
请您参考如下方法:
Try 没有性能开销;您可以安全地使用它;如果您抛出异常,则会产生性能开销。
另一方面,优化不在 try block 内执行;但这不会产生开销,除非您有适当的代码(您可以引用 try-catch performance )。
来自 msdn performance tips : “查找和设计大量异常的代码可以带来不错的性能胜利。请记住,这与 try/catch block 无关:您只会在抛出实际异常时承担成本。您可以使用尽可能多的 try/catch block ,随心所欲。无偿使用异常是你失去性能的地方。例如,你应该远离诸如使用异常控制流之类的事情。“
