簡體   English   中英

如何在.NET中捕獲內部異常?

[英]How to catch inner exception in .NET?

如何在.NET中捕獲內部異常? 我需要檢查2個數據庫以獲取記錄。 如果找不到記錄,數據庫代碼會拋出異常,因此我想檢查第二個數據庫:

Try
     # Code to look in database 1
Catch ex as DataServiceQueryException
     Try
          # Code to look in database 2
     Catch ex2 as DataServiceQueryException
          throw New DataServiceQueryException(ex.Message, ex2) # Fails here
     End Try
Catch ex as Exception # Why doesn't ex2 land here?
   # Tell user that data was not found in either database
End Try

上面的偽代碼在'Fails here ,ex2永遠不會被我的代碼處理。

我該如何正確處理內部異常?

您當前代碼不起作用的原因是,一旦您進入catch部分,您就已經離開了try塊。 相反,這樣做:

Try
   ''# Check Database 1
Catch
    Try
        ''# Check Database 2
    Catch
         ''# Tell the user that data was not found in either database
    End Try
End Try

或者像這樣:

Dim FoundFlag as Boolean = False
Try
    ''# Check Database 1
    FoundFlag = True
    ''# Best if you can just return "False" and avoid the exception altogether
Catch
End Try

If Not FoundFlag Then
    Try
        ''# Check Database 2
        FoundFlag = True
    Catch
    End Try
End If

If Not FoundFlag Then
     ''# Tell the user that data was not found in any database
End If

根據定義,內部異常已經被處理並重新打包為另一個例外。 您必須處理外部異常,然后在必要時/適當地處理外部異常的catch塊中的內部異常。

首先,如果你正在使用try / catch,你應該最終有一個清理資源。 話雖這么說,嵌套try / catch阻止了我們通常代碼味道。 你必須這樣實現嗎? 為什么服務器會失敗? 為什么數據層不能傳遞狀態消息? 例外情況應該是“例外”。

如果你必須使用例外,“Joel Coehoorn”的方式似乎很好。

我會說,基於偽代碼,這是因為你在第7行拋出的異常位於第3行的“try”塊內,所以第9行的“catch”根本不適用。

編輯:喬爾說的話。

我同意Joel,我希望進一步建議你坐下來決定你真正希望發生以下哪種情況,然后進行相應的編碼。

情況A.如果db1中存在record11,則檢查db2中是否存在record22

try{
  getRecord11;

  try
  {
    getRecord22;
  }
  catch ex22
  {
    saySorry2;
  }
}
catch ex11
{
  saySorry1;
}

情況B.如果db1中不存在record11,則檢查db2中是否存在record22

try{
  getRecord11;
}
catch ex11
{
  saySorry1;

  try
  {
    getRecord22;
  }
  catch ex22
  {
    saySorry2;
  }
}

case C.從db1獲取record11。 無論db1結果如何,從db2獲取record22。

try{
  getRecord11;
}
catch ex11
{
  saySorry1;
}

try
{
  getRecord22;
}
catch ex22
{
  saySorry2;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM