简体   繁体   English

多次抛出异常

[英]Throwing exceptions multiple times

I have the following code: 我有以下代码:

    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));
        }
    }

The above code will get the last inserted ID from an Access database for me. 上面的代码将从我的Access数据库中获取最后插入的ID。 Now, to do this, Button_Click_Action will call GetLastAddedID and that will call GetLastAddedIDHelper . 现在,要做到这一点, Button_Click_Action将调用GetLastAddedID ,并将调用GetLastAddedIDHelper When a exception occurs in GetLastAddedIDHelper , I throw the exception up to the main method Button_Click_Action . GetLastAddedIDHelper发生exception时,我将异常扔给主方法Button_Click_Action

I'm wondering if I'm doing this the correct way like, is the throw in GetLastAddedID necessary, should I use throw instead of throw ex , ...? 我想知道我是否以正确的方式执行此操作,例如是否需要GetLastAddedID的throw,是否应该使用throw而不是throw ex ... ...?

The exception handling in GetLastAddedIDHelper and GetLastAddedID do not serve any useful purpose in this case. 在这种情况下, GetLastAddedIDHelperGetLastAddedID的异常处理没有任何用处。 Your intent, it would seem, is to simply catch the exception and then do nothing with it except to rethrow it. 看来,您的意图是简单地捕获异常,然后对异常进行任何处理,除非将其重新抛出。 If that is the case then why bother catching it all? 如果是这样的话,那为什么还要麻烦全部解决呢? Just let the exception propagate up the stack until an exception handler that can handle it gets it, in the Button_Click_Action method in this case. 只要让异常在堆栈中传播,直到可以处理该异常的异常处理程序将其释放即可,在这种情况下,请使用Button_Click_Action方法。

In this example your exception handling is actually harmful because throw ex will mess up your stack trace. 在此示例中,您的异常处理实际上是有害的,因为throw ex会弄乱您的堆栈跟踪。 You want to use throw instead. 您想改用throw

You probably want to do throw; 你可能想throw; because throw ex; 因为throw ex; will reset the stack trace. 将重置堆栈跟踪。

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

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