簡體   English   中英

如何強制執行到 Catch 塊?

[英]How Can I Force Execution to the Catch Block?

我想知道可以try..catch強制執行進入catch並在那里運行代碼嗎?

這里示例代碼:

try {
    if (AnyConditionTrue) {
      // run some code
    }
    else {
      // go catch
    }
} catch (Exception) {
    // run some code here...
}

與其在else拋出異常,我建議您將catch的代碼提取到一個方法中,然后從 else 中調用它

try
{
    if (AnyConditionTrue)
    {
        MethodWhenTrue();
    }
    else
    {
        HandleError();
    }
}
catch(Exception ex)
{
    HandleError();
}
   try{
      if (AnyConditionTrue){
              //run some code
               }
      else{
              throw new Exception();
          }
   }
   catch(){

      //run some code here...

   }

但就像 Yuck 所說的,我不推薦這個。 您應該退后一步,了解您的設計以及您希望實現的目標。 有一個更好的方法來做到這一點(即使用正常的條件流,而不是異常處理)。

是的,你必須拋出異常:

  try
  {
    throw new Exception("hello");
  }
  catch (Exception)
  {

     //run some code here...
  }

一種拋出Exception並跳轉到Catch的有效方法,如下所示:

try
{
   throw new Exception("Exception Message");
}
catch (Exception e)
{
   // after the throw, you will land here
}
if(conditiontrue)
{

}
else{
    throw new Exception();
}

正如cadrel所說,但是通過一個Exception來提供更多的反饋,會在innerException中顯示:

try
{
    if (AnyConditionTrue)
    {
        MethodWhenTrue();
    }
    else
    {
        HandleError(new Exception("AnyCondition is not true"));
    }
}
catch (Exception ex)
{
    HandleError(ex);
}

...

private void HandleError(Exception ex) {
    throw new ApplicationException("Failure!", ex);
}

如果你想“強迫”嘗試捕獲,只是故意做一些愚蠢的事情,像這樣:

List<string> cc = null;
foreach (string c in cc) {}
public class CustomException: Exception
{
     public CustomException(string message)
        : base(message) { }

}

//

if(something == anything)
{
   throw new CustomException(" custom text message");
}

你可以試試這個

是的,如果您throw您打算從 try 中catch的異常,它將在 catch 部分中捕獲。

我不得不問你為什么要這樣做? 異常處理並不意味着要替代控制流。

我認為你想要的是一個finally塊: http : //msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.80).aspx

看到這個

try
 {
     doSomething();
 }
catch
 {
     catchSomething();
     throw an error
 } 
finally
 {
     alwaysDoThis();
 }

如果/當您這樣做時,情況會有所不同:

try
 {
     doSomething(); 
 }
 catch
 {
     catchSomething(); 
     throw an error
 }
  alwaysDoThis();// will not run on error (in the catch) condition

最后一個實例,如果發生錯誤,catch 將執行,但不是alwaysDoThis(); . 當然,您仍然可以像往常一樣進行多次catch

輕微的復活,但我想添加一個樣本(主要像其他人一樣)和一個用例。

public int GetValueNum(string name)
    {
        int _ret = 0;

        try
        {
            Control c = (extendedControls.Single(s => s.ValueName == name) as Control);

            if (c.GetType() == typeof(ExtendedNumericUpDown))
                _ret = (int)((ExtendedNumericUpDown)c).Value;

            else
                throw new Exception();
        }

        catch
        {
            throw new InvalidCastException(String.Format("Invalid cast fetching .Value value for {0}.\nExtendedControllerListener.GetValueNum()", name));
        }

        return _ret;
    }

就我而言,我有自定義控件 - 一些使用基本 Windows.Forms 控件的控件,但添加了兩個布爾值和一個用於跟蹤的字符串,並且還自動注冊到 Singleton List<T>以便可以正確獲取它們無需深入控制容器(它是選項卡形式)。

在這種情況下,我創建了一些方法來通過名稱字符串輕松獲取值( .Value, .Text, .Checked, .Enabled )。 .Value的情況下,並非所有Control對象都有它。 如果擴展控件的類型不是ExtendedNumericUpDown ,則它是InvalidCastException因為不應針對該類型的控件調用該方法。 這不是流,而是無效轉換的規定用法。 由於Control自然沒有.Value屬性,Visual Studio 不會讓我只是強制嘗試並在之后失敗。

您可以拋出異常以強制捕獲

throw new Exception(...);

你為什么要捕捉異常? 為什么不直接在“else”塊中運行代碼? 如果你必須這樣做,就拋出一個新的異常

throw new Exception();

暫無
暫無

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

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