繁体   English   中英

多次抛出异常

[英]Throwing exceptions multiple times

我有以下代码:

    static int GetLastAddedIDHelper(OleDbConnection connection)
    {
        try
        {
            // Init variables.
            OleDbCommand command = null;
            string cmdText = "SELECT @@IDENTITY";

            if (connection != null)
                command = new OleDbCommand(cmdText, connection);
            else
                throw new ArgumentNullException("connection", "The connection was passed as null. Therefore the globally used connection is used but was never set.");

            return (int)command.ExecuteScalar();
        }
        catch (Exception ex) { throw ex; }
    }

    public static int GetLastAddedID()
    {
        try
        {
            return GetLastAddedIDHelper(_Connection);
        }
        catch (Exception ex) { throw ex; }
    }

    private void Button_Click_Action()
    {
        try
        {
            int i = AccessDbServiceBase.GetLastAddedID();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ExceptionHandler.GetExceptionMessage(ex));
        }
    }

上面的代码将从我的Access数据库中获取最后插入的ID。 现在,要做到这一点, Button_Click_Action将调用GetLastAddedID ,并将调用GetLastAddedIDHelper GetLastAddedIDHelper发生exception时,我将异常扔给主方法Button_Click_Action

我想知道我是否以正确的方式执行此操作,例如是否需要GetLastAddedID的throw,是否应该使用throw而不是throw ex ... ...?

在这种情况下, GetLastAddedIDHelperGetLastAddedID的异常处理没有任何用处。 看来,您的意图是简单地捕获异常,然后对异常进行任何处理,除非将其重新抛出。 如果是这样的话,那为什么还要麻烦全部解决呢? 只要让异常在堆栈中传播,直到可以处理该异常的异常处理程序将其释放即可,在这种情况下,请使用Button_Click_Action方法。

在此示例中,您的异常处理实际上是有害的,因为throw ex会弄乱您的堆栈跟踪。 您想改用throw

你可能想throw; 因为throw ex; 将重置堆栈跟踪。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM