簡體   English   中英

如果捕獲到異常,如何跳過進一步執行

[英]How to skip further execution if exception is catch

我正在使用Web應用程序。我正在使用aspx頁面作為api。從函數我正在調用函數2.兩個函數都有try和catch塊。

 Function1()
    {
      try
      {
        int b = function2()
      }
      catch(Exception ex)
      {
        Response.Write(ex.Tostring());
      }

    }

   public int Function2()
    {
      int a= 0;
      try
      {
        a=8;
       return a;
      }
      catch(Exception ex)
      {
       Response.Write(ex.Tostring());
       return a;
      }

    }

如果第二個功能中有錯誤捕獲,我想跳過進一步執行(function1)。我可以在第二個功能的catch塊中使用break嗎?

Function2 catch塊中,不return而是throw異常,因此它將再次在function1 catch塊中被catch

Function1()
{
    try
    {
        int b = function2()
    }
    catch(Exception ex)
    {
        Response.Write(ex.Tostring());
    }
}

public int Function2()
{
    int a= 0;
    try
    {
        a=8;
        return a;
    }
    catch(Exception ex)
    {
        Response.Write(ex.Tostring());
        throw; //<----- here
    }
}

根據關於中斷的文檔,在給定的示例中,您無法中斷第二個函數以停止進一步執行Function1。 但是你可以做這樣的事情。

Function1()
{
    try
    {
        int b = function2()
        if (b = 0)
            break; // Or maybe a return of an error.
    }
    catch(Exception ex)
    {
        Response.Write(ex.Tostring());
    }
}

暫無
暫無

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

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