如果异常被捕获,如何跳过进一步执行 [英] How to skip further execution if exception is catch

查看:50
本文介绍了如果异常被捕获,如何跳过进一步执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用web应用程序。我使用aspx页面作为api.From函数我调用函数2.Both函数有try和catch块。



I am using web application.I am using aspx page as api.From function I am calling function 2.Both function have try and catch block.

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)第二个funtion.can我在第二个函数的catch块中使用break。



我尝试过:





I want to skip further execution(function1) if error catch in second funtion.can I use break in second function's catch block.

What I have tried:

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处理程序中:

The simplest solution is to re-throw the exception, so it's caught in the Function1 handler:
public int Function2()
    {
    int a= 0;
    try
       {
       a=8;
       return a;
       }
    catch(Exception ex)
       {
       Response.Write(ex.Tostring());
       throw;
       }
   }



但是如果在其他地方使用Function2那么我很想这样做:


But if Function2 is used in other places then I'd be tempted to do it like this:

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

然后你可以从Function1调用它,知道它可以处理它:

You can then call it from Function1 knowing that it can handle it:

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


这篇关于如果异常被捕获,如何跳过进一步执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆