简体   繁体   中英

Try Catch loop not intercept exception

I'm implementing a windows service that synchronizes a SQL database and a DB2 database. To connect to the old DB2 database, I use a DLL. I have a try catch cycle in which I write from the sql database to the db2. No exception appears and the service closes automatically. is it possible that the DLL does not generate any exception and automatically closes the service?

I use this code:

public bool InsertProcessToAS400(iDB2Connection cn, Order order)
{
    bool result = false;
    try
    {   
        var code = GetCodeOfDdtConnected(cn, order.Code);
        iDB2Command cmd = cn.CreateCommand();

        cmd.CommandText = $"INSERT INTO PCM00F " +
                          $"(Code)" +
                          $"VALUES(@P1)";

        var p = new iDB2Parameter("@P1", iDB2DbType.iDB2VarChar);
        p.Value = code; cmd.Parameters.Add(p);

        cmd.ExecuteNonQuery();   // <- This close the service

        result = true;
    }
    catch (Exception ex)
    {
        log.Error("An error occurred while Synchronizer (INSERT): ", ex);
        result = false;
    }
    finally
    {
        cmd.Dispose(); cmd = null;
    }

    return result;
}

Is it possible that it closes because the query input parameter is wrong? How can I intercept an external dll error if an exception is not triggered? thanks a lot

I solved it with this code:

public bool InsertProcessToAS400(iDB2Connection cn, Order order)
{
      bool result = false;
      try
      {
          DB2Transaction myTrans;
          var code = GetCodeOfDdtConnected(cn, order.Code);
          iDB2Command cmd = cn.CreateCommand();
          // Start a local transaction
          myTrans = cn.BeginTransaction();
          // Assign transaction object for a pending local transaction
          cmd.Transaction = myTrans;

          cmd.CommandText =$"INSERT INTO PCM00F " +
          $"(Code)" +
          $"VALUES(@P1)";

          var p = new iDB2Parameter("@P1", iDB2DbType.iDB2VarChar);
          p.Value = code; cmd.Parameters.Add(p);

          cmd.ExecuteNonQuery();
          myTrans.Commit();
          result = true;
       }
       catch (Exception ex)
       {
           myTrans.Rollback();
           log.Error("An error occurred while Synchronizer (INSERT): ", ex);
           result = false;
       }
       finally
       {
           cmd.Dispose(); cmd = null;
       }

       return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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