try catch 塊的使用原則

來源:互聯網
上載者:User

舉一個NHibernate的例子

ISession session;

ITransaction tx;

try

{

session = factory.OpenSession();

tx = session.BeginTransaction();

// do database work

tx.Commit();

session.Close();

}

catch (Exception ex)

{

tx.Rollback();

session.Close();

// further exception handling

}

I can’t claim to know the inner workings of OpenSession but if there’s a chance it throws and surfaces an exception, the catch is going to access a null reference, tx. General advice:

Acquire Resource;

Try

Do Something with Resource

Catch

Do something

Finally

Release Resource

Actually there’s a semantic implication of OpenSession. To me it should either return a valid ISession reference to an open reference or it should throw an exception. The same goes for BeginTransaction. So, IMHO this is how to write it (my 2c):

ISession session = factory.OpenSession();

try

{

  ITransaction tx = session.BeginTransaction();

  try

  {

    // do db work

    tx.Commit();

  }

  catch

  {

    tx.Rollback();

  }

}

finally

{

  session.Close();

}

Both session in finally and tx in catch will be valid references provided that OpenSession and BeginTransaction returns what they atomically should return, i.e. an open session in the former case and a started transaction in the latter case.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.