zoukankan      html  css  js  c++  java
  • try catch 块的使用原则

    举一个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.


  • 相关阅读:
    IO流(读取键盘录入)
    IO 流 自定义字节流的缓冲区-read 和write 的特点
    IO流 字节流的缓冲区
    IO流 拷贝图片
    IO流-字节流File读写操作
    IO流 带行号的缓冲区
    IO流(装饰设计模式)
    IO流-ReadLine方法的原理 自定义BufferedReader
    IO流 Buffered 综合练习
    IO流 BufferedWriter
  • 原文地址:https://www.cnblogs.com/idior/p/139182.html
Copyright © 2011-2022 走看看