You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@turbine.apache.org by Mathieu Frenette <ma...@freeborders.com> on 2002/02/21 18:27:02 UTC

[PATCH] Standardizing OM for throwing TorqueException

What a daunting task, but I did it!

It's my first involvement in Open Source, CVS, and Torque, so please be
indulgent. ;-) I did my best with this action item.  Please let me know if I
did anything wrong, so I can improve it next time.

I used WinCVS to produce the diff, but I don't know if it's "unidiff"
compliant, as you mentionned that "unidiff" was preferred.  Also, I left all
file diffs in the same text file.  Let me know if this poses a problem.

In addition to the patch file, I included a zip containing all the files
after modification, just in case you need them.

Here's my work report:

*********************************

* Modified the following files for using TorqueException, and fixed javadoc
comments:

    Torque.java
    BasePeer.java
    SqlExpression.java
    Criteria.java

    MapBuilder.vm
    Object.vm
    Peer.vm


* Decided to leave the IdGenerator interface unchanged for now, because
changing it to throw TorqueException instead of Exception might break
people's code that implement this interface.  However, it would not affect
code that is _using_ this interface.  We should discuss how this will be
addressed.  If we settle to change it in some way, I can take care of it,
including Torque classes which implement it.

* Simplified try/finally clauses (but only when it was in the scope of a
required modification) from this style:

    dbCon = null;
    try
    {
      dbCon = Torque.getConnection(dbName);
      doDelete(criteria, dbCon);
    }
    finally
    {
      if (dbCon == null)
          Torque.releaseConnection(dbCon);
    }

to this style:

    dbCon = Torque.getConnection(dbName);
    try
    {
      doDelete(criteria, dbCon);
    }
    finally
    {
      Torque.releaseConnection(dbCon);
    }

Please confirm with me that this doesn't affect the intended semantic.  For
example, I assumed that if .getConnection() failed, then
.releaseConnection() doesn't need to be called.

* Tried to avoid excessive exception wrapping.  For example, in cases where
SQLException, DataSetException and TorqueException are thrown by a portion
of code, I explicitly catch the two first individually, and let
TorqueException fall through.  (I could have caught Exception and wrap it
into TorqueException, but that would allow TorqueExceptions to be wrapped
many levels deep, which we don't want).

* Used the following style of try/catch/finally in order to simplify
handling of cases where the finally clause may throw exceptions to be
caught.  This is the cleanest way I know of handling this kind of situation:

    try
    {
        try
        {
            // Do something which may throw SQLException
        }
        finally
        {
            // Clean-up which may throw SQLException
        }
    }
    catch(SQLException e)
    {
        throw new TorqueException(e);
    }

*********************************

Comments would be appreciated! :-)

Looking forward to hearing from you...

-- Mathieu

Re: [PATCH] Standardizing OM for throwing TorqueException (3/3)

Posted by Daniel Rall <dl...@finemaltcoding.com>.
-
     }
 
 
@@ -164,36 +174,36 @@
 
         #foreach ($child in $col.Children)
     /** A key representing a particular subclass */
-    public static final $col.JavaNative CLASSKEY_$child.Key.toUpperCase() = 
+    public static final $col.JavaNative CLASSKEY_$child.Key.toUpperCase() =
         $quote$child.Key$quote;
 
     /** A class that can be returned by this peer. */
-    public static final String CLASSNAME_$child.Key.toUpperCase() = 
+    public static final String CLASSNAME_$child.Key.toUpperCase() =
         "${package}.$child.ClassName";
 
     /** A class that can be returned by this peer. */
-    public static final Class CLASS_$child.Key.toUpperCase() = 
+    public static final Class CLASS_$child.Key.toUpperCase() =
         initClass(CLASSNAME_$child.Key.toUpperCase());
         #end
     #end
 #end
 
-    /** 
-     * Method to do inserts 
+    /**
+     * Method to do inserts
      */
-    public static ObjectKey doInsert( Criteria criteria ) throws Exception
+    public static ObjectKey doInsert( Criteria criteria ) throws TorqueException
     {
         return $basePrefix${table.JavaName}Peer
             .doInsert( criteria, (DBConnection) null );
     }
 
-    /** 
+    /**
      * Method to do inserts.  This method is to be used during a transaction,
-     * otherwise use the doInsert(Criteria) method.  It will take care of 
-     * the connection details internally. 
+     * otherwise use the doInsert(Criteria) method.  It will take care of
+     * the connection details internally.
      */
-    public static ObjectKey doInsert( Criteria criteria, DBConnection dbCon ) 
-        throws Exception
+    public static ObjectKey doInsert( Criteria criteria, DBConnection dbCon )
+        throws TorqueException
     {
      #foreach ($col in $table.Columns)
          #set ( $cup=$col.Name.toUpperCase() )
@@ -209,10 +219,10 @@
                     criteria.add($cup, 1);
                 }
                 else
-                {   
+                {
                     criteria.add($cup, 0);
                 }
-            }                     
+            }
          }
          #elseif ($col.isBooleanChar())
         // check for conversion from boolean to Y/N
@@ -226,16 +236,16 @@
                     criteria.add($cup, "Y");
                 }
                 else
-                {   
+                {
                     criteria.add($cup, "N");
                 }
-            }                     
+            }
          }
          #end
      #end
 
         // Set the correct dbName if it has not been overridden
-        // criteria.getDbName will return the same object if not set to 
+        // criteria.getDbName will return the same object if not set to
         // another value so == check is okay and faster
         if ( criteria.getDbName() == Torque.getDefaultDB() )
         {
@@ -252,7 +262,7 @@
     }
 
     /** Add all the columns needed to create a new object */
-    public static void addSelectColumns (Criteria criteria) throws Exception
+    public static void addSelectColumns (Criteria criteria) throws TorqueException
     {
     #foreach ($col in $table.Columns)
         #set ( $cup=$col.Name.toUpperCase() )
@@ -261,38 +271,51 @@
     }
 
 
-    /** 
+    /**
      * Create a new object of type cls from a resultset row starting
      * from a specified offset.  This is done so that you can select
      * other rows than just those needed for this object.  You may
      * for example want to create two objects from the same row.
      */
-    public static $table.JavaName row2Object (Record row, 
-                                              int offset, 
-                                              Class cls ) 
-        throws Exception
-    {
-        $table.JavaName obj = ($table.JavaName)cls.newInstance();
-        populateObject(row, offset, obj);
-        #if ($addSaveMethod)
-            obj.setModified(false);
-        #end
-        obj.setNew(false);
+    public static $table.JavaName row2Object (Record row,
+                                              int offset,
+                                              Class cls )
+        throws TorqueException
+    {
+        try
+        {
+            $table.JavaName obj = ($table.JavaName)cls.newInstance();
+            populateObject(row, offset, obj);
+            #if ($addSaveMethod)
+                obj.setModified(false);
+            #end
+            obj.setNew(false);
 
-        return obj;
+            return obj;
+        }
+        catch (InstantiationException e)
+        {
+            throw new TorqueException(e);
+        }
+        catch (IllegalAccessException e)
+        {
+            throw new TorqueException(e);
+        }
     }
 
-    /** 
+    /**
      * Populates an object from a resultset row starting
      * from a specified offset.  This is done so that you can select
      * other rows than just those needed for this object.  You may
      * for example want to create two objects from the same row.
      */
-    public static void populateObject (Record row, 
-                                       int offset, 
-                                       $table.JavaName obj ) 
-        throws Exception
+    public static void populateObject (Record row,
+                                       int offset,
+                                       $table.JavaName obj )
+        throws TorqueException
     {
+        try
+        {
         #set ( $n=0 )
         #foreach ($col in $table.Columns)
             #if ($col.isBooleanChar())
@@ -314,49 +337,54 @@
             #end
                 #set ( $n = $n + 1 )
         #end
+        }
+        catch (DataSetException e)
+        {
+            throw new TorqueException(e);
+        }
     }
 
     /** Method to do selects */
-    public static Vector doSelect( Criteria criteria ) throws Exception
+    public static Vector doSelect( Criteria criteria ) throws TorqueException
     {
-        return populateObjects( doSelectVillageRecords(criteria) ); 
+        return populateObjects( doSelectVillageRecords(criteria) );
     }
 
 
     /** Method to do selects within a transaction */
-    public static Vector doSelect( Criteria criteria, 
-                                   DBConnection dbCon ) 
-        throws Exception
+    public static Vector doSelect( Criteria criteria,
+                                   DBConnection dbCon )
+        throws TorqueException
     {
-        return populateObjects( doSelectVillageRecords(criteria, dbCon) ); 
+        return populateObjects( doSelectVillageRecords(criteria, dbCon) );
     }
 
-    /** 
+    /**
      * Grabs the raw Village records to be formed into objects.
      * This method handles connections internally.  The Record objects
      * returned by this method should be considered readonly.  Do not
      * alter the data and call save(), your results may vary, but are
      * certainly likely to result in hard to track MT bugs.
      */
-    public static Vector doSelectVillageRecords( Criteria criteria ) 
-        throws Exception
+    public static Vector doSelectVillageRecords( Criteria criteria )
+        throws TorqueException
     {
         return $basePrefix${table.JavaName}Peer
             .doSelectVillageRecords(criteria, (DBConnection) null);
     }
 
-    /** 
+    /**
      * Grabs the raw Village records to be formed into objects.
-     * This method should be used for transactions 
+     * This method should be used for transactions
      */
-    public static Vector doSelectVillageRecords( Criteria criteria, 
-                                                 DBConnection dbCon ) 
-        throws Exception
+    public static Vector doSelectVillageRecords( Criteria criteria,
+                                                 DBConnection dbCon )
+        throws TorqueException
     {
     #if ($targetDatabase == "postgresql" && $table.requiresTransactionInPostgres())
          // stuff for postgresql problem.....
          criteria.setBlobFlag();
-    #end 
+    #end
 
         if (criteria.getSelectColumns().size() == 0)
         {
@@ -377,10 +405,10 @@
                     criteria.add($cup, 1);
                 }
                 else
-                {   
+                {
                     criteria.add($cup, 0);
                 }
-            }                     
+            }
          }
          #elseif ($col.isBooleanChar())
         // check for conversion from boolean to Y/N
@@ -394,16 +422,16 @@
                     criteria.add($cup, "Y");
                 }
                 else
-                {   
+                {
                     criteria.add($cup, "N");
                 }
-            }                     
+            }
          }
          #end
      #end
 
         // Set the correct dbName if it has not been overridden
-        // criteria.getDbName will return the same object if not set to 
+        // criteria.getDbName will return the same object if not set to
         // another value so == check is okay and faster
         if ( criteria.getDbName() == Torque.getDefaultDB() )
         {
@@ -421,12 +449,12 @@
         }
     }
 
-    /** 
+    /**
      * The returned vector will contain objects of the default type or
      * objects that inherit from the default.
      */
-    public static Vector populateObjects(Vector records) 
-        throws Exception
+    public static Vector populateObjects(Vector records)
+        throws TorqueException
     {
         Vector results = new Vector(records.size());
 
@@ -449,16 +477,16 @@
 #if ($table.ChildrenColumn)
 
     #set ($col = $table.ChildrenColumn)
-    /** 
+    /**
      * The returned Class will contain objects of the default type or
      * objects that inherit from the default.
      */
-    public static Class getOMClass(Record record, int offset) 
-        throws Exception
+    public static Class getOMClass(Record record, int offset)
+        throws TorqueException
     {
     #if ($col.isEnumeratedClasses())
             Class omClass = null;
-            $col.JavaNative classKey = 
+            $col.JavaNative classKey =
                 record.getValue(offset-1 + $col.Position)
                 .$col.VillageMethod;
         #set ($if = "if")
@@ -479,20 +507,20 @@
             }
             return omClass;
     #else
-            return Class.forName( 
+            return Class.forName(
                 record.getValue(offset-1 + $col.Position).asString());
     #end
     }
-    
+
 #end
 
-    /** 
-     * The class that the Peer will make instances of. 
+    /**
+     * The class that the Peer will make instances of.
      * If the BO is abstract then you must implement this method
      * in the BO.
      */
-    public static Class getOMClass() 
-        throws Exception
+    public static Class getOMClass()
+        throws TorqueException
     {
     #if ($table.isAbstract())
         String error = "You must implement the getOMClass method in your";
@@ -508,24 +536,24 @@
 #if (!$table.isAlias())
 
     /**
-     * Method to do updates. 
+     * Method to do updates.
      *
      * @param Criteria object containing data that is used to create the UPDATE statement.
      */
-    public static void doUpdate(Criteria criteria) throws Exception
+    public static void doUpdate(Criteria criteria) throws TorqueException
     {
          $basePrefix${table.JavaName}Peer
             .doUpdate( criteria, (DBConnection) null );
     }
 
-    /** 
+    /**
      * Method to do updates.  This method is to be used during a transaction,
-     * otherwise use the doUpdate(Criteria) method.  It will take care of 
-     * the connection details internally. 
+     * otherwise use the doUpdate(Criteria) method.  It will take care of
+     * the connection details internally.
      *
      * @param Criteria object containing data that is used to create the UPDATE statement.
      */
-    public static void doUpdate(Criteria criteria, DBConnection dbCon) throws Exception
+    public static void doUpdate(Criteria criteria, DBConnection dbCon) throws TorqueException
     {
         Criteria selectCriteria = new
             Criteria(DATABASE_NAME, 2);
@@ -543,10 +571,10 @@
                     criteria.add($cup, 1);
                 }
                 else
-                {   
+                {
                     criteria.add($cup, 0);
                 }
-            }                     
+            }
          }
          #elseif ($col.isBooleanChar())
         // check for conversion from boolean to int
@@ -560,10 +588,10 @@
                     criteria.add($cup, "Y");
                 }
                 else
-                {   
+                {
                     criteria.add($cup, "N");
                 }
-            }                     
+            }
          }
          #end
          #if($col.isPrimaryKey())
@@ -572,7 +600,7 @@
      #end
 
         // Set the correct dbName if it has not been overridden
-        // criteria.getDbName will return the same object if not set to 
+        // criteria.getDbName will return the same object if not set to
         // another value so == check is okay and faster
         if ( criteria.getDbName() == Torque.getDefaultDB() )
         {
@@ -588,26 +616,26 @@
         }
     }
 
-    /** 
+    /**
      * Method to do deletes.
      *
      * @param Criteria object containing data that is used DELETE from database.
      */
-     public static void doDelete(Criteria criteria) throws Exception
+     public static void doDelete(Criteria criteria) throws TorqueException
      {
          $basePrefix${table.JavaName}Peer
             .doDelete ( criteria, (DBConnection) null );
      }
 
-    /** 
+    /**
      * Method to do deletes.  This method is to be used during a transaction,
-     * otherwise use the doDelete(Criteria) method.  It will take care of 
-     * the connection details internally. 
+     * otherwise use the doDelete(Criteria) method.  It will take care of
+     * the connection details internally.
      *
      * @param Criteria object containing data that is used DELETE from database.
      */
-     public static void doDelete(Criteria criteria, DBConnection dbCon) 
-        throws Exception
+     public static void doDelete(Criteria criteria, DBConnection dbCon)
+        throws TorqueException
      {
      #foreach ($col in $table.Columns)
          #set ( $cup=$col.Name.toUpperCase() )
@@ -623,10 +651,10 @@
                     criteria.add($cup, 1);
                 }
                 else
-                {   
+                {
                     criteria.add($cup, 0);
                 }
-            }                     
+            }
          }
          #elseif ($col.isBooleanChar())
         // check for conversion from boolean to Y/N
@@ -640,16 +668,16 @@
                     criteria.add($cup, "Y");
                 }
                 else
-                {   
+                {
                     criteria.add($cup, "N");
                 }
-            }                     
+            }
          }
          #end
      #end
 
         // Set the correct dbName if it has not been overridden
-        // criteria.getDbName will return the same object if not set to 
+        // criteria.getDbName will return the same object if not set to
         // another value so == check is okay and faster
         if ( criteria.getDbName() == Torque.getDefaultDB() )
         {
@@ -666,13 +694,13 @@
      }
 
     /** Method to do selects */
-    public static Vector doSelect($table.JavaName obj) throws Exception
+    public static Vector doSelect($table.JavaName obj) throws TorqueException
     {
         return doSelect(buildCriteria(obj));
     }
 
     /** Method to do inserts */
-    public static void doInsert( $table.JavaName obj ) throws Exception
+    public static void doInsert( $table.JavaName obj ) throws TorqueException
     {
         #if ($table.IdMethod.equals("none"))
         doInsert(buildCriteria(obj));
@@ -686,7 +714,7 @@
     /**
      * @param obj the data object to update in the database.
      */
-    public static void doUpdate($table.JavaName obj) throws Exception
+    public static void doUpdate($table.JavaName obj) throws TorqueException
     {
         doUpdate(buildCriteria(obj));
     }
@@ -694,20 +722,20 @@
     /**
      * @param obj the data object to delete in the database.
      */
-    public static void doDelete($table.JavaName obj) throws Exception
+    public static void doDelete($table.JavaName obj) throws TorqueException
     {
         doDelete(buildCriteria(obj));
     }
 
-    /** 
+    /**
      * Method to do inserts.  This method is to be used during a transaction,
-     * otherwise use the doInsert($table.JavaName) method.  It will take 
-     * care of the connection details internally. 
+     * otherwise use the doInsert($table.JavaName) method.  It will take
+     * care of the connection details internally.
      *
      * @param obj the data object to insert into the database.
      */
     public static void doInsert( $table.JavaName obj, DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
         #if ($table.IdMethod.equals("none"))
         doInsert(buildCriteria(obj), dbCon);
@@ -720,25 +748,25 @@
 
     /**
      * Method to do update.  This method is to be used during a transaction,
-     * otherwise use the doUpdate($table.JavaName) method.  It will take 
-     * care of the connection details internally. 
+     * otherwise use the doUpdate($table.JavaName) method.  It will take
+     * care of the connection details internally.
      *
      * @param obj the data object to update in the database.
      */
     public static void doUpdate($table.JavaName obj, DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
         doUpdate(buildCriteria(obj), dbCon);
     }
     /**
      * Method to delete.  This method is to be used during a transaction,
-     * otherwise use the doDelete($table.JavaName) method.  It will take 
-     * care of the connection details internally. 
+     * otherwise use the doDelete($table.JavaName) method.  It will take
+     * care of the connection details internally.
      *
      * @param obj the data object to delete in the database.
      */
     public static void doDelete($table.JavaName obj, DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
         doDelete(buildCriteria(obj), dbCon);
     }
@@ -767,13 +795,13 @@
     #set ($retrieveMethod = "retrieveByPK")
 #end
 
-    /** 
+    /**
      * Retrieve a single object by pk
      *
      * @param ObjectKey pk
      */
     public static $table.JavaName ${retrieveMethod}( ObjectKey pk )
-        throws Exception
+        throws TorqueException
     {
         DBConnection db = null;
         $table.JavaName retVal = null;
@@ -790,14 +818,14 @@
         return(retVal);
     }
 
-    /** 
+    /**
      * Retrieve a single object by pk
      *
      * @param ObjectKey pk
      * @param DBConnection dbcon
      */
     public static $table.JavaName ${retrieveMethod}( ObjectKey pk, DBConnection dbcon )
-        throws Exception
+        throws TorqueException
     {
 
         Criteria criteria = new Criteria();
@@ -815,7 +843,7 @@
         Vector v = doSelect(criteria, dbcon);
         if ( v.size() != 1)
         {
-            throw new Exception("Failed to select one and only one row.");
+            throw new TorqueException("Failed to select one and only one row.");
         }
         else
         {
@@ -826,7 +854,7 @@
 
 #if ($table.PrimaryKeys.size() > 1)
 #set ( $comma = false )
-    /** 
+    /**
      * retrieve object using using pk values.
      *
 #foreach ($col in $table.PrimaryKeys)
@@ -842,14 +870,14 @@
     #if ($comma),#end $cjtype $clo
         #set ( $comma = true )
 #end
-        ) throws Exception
+        ) throws TorqueException
     {
         DBConnection db = null;
         $table.JavaName retVal = null;
        try
         {
            db = Torque.getConnection( DATABASE_NAME );
-           retVal = retrieveByPK( 
+           retVal = retrieveByPK(
            #set ( $comma = false )
            #foreach ($col in $table.PrimaryKeys)
          #set ( $clo=$col.Name.toLowerCase() )
@@ -864,10 +892,10 @@
               Torque.releaseConnection(db);
         }
         return(retVal);
-    }   
+    }
 
 #set ( $comma = false )
-    /** 
+    /**
      * retrieve object using using pk values.
      *
 #foreach ($col in $table.PrimaryKeys)
@@ -884,9 +912,9 @@
     #if ($comma),#end $cjtype $clo
         #set ( $comma = true )
 #end
-       ,DBConnection dbcon ) throws Exception
+       ,DBConnection dbcon ) throws TorqueException
     {
-    
+
         Criteria criteria = new Criteria(5);
 #foreach ($col in $table.PrimaryKeys)
     #set ( $cup=$col.Name.toUpperCase() )
@@ -896,7 +924,7 @@
         Vector v = doSelect(criteria, dbcon);
         if ( v.size() != 1)
         {
-            throw new Exception("Failed to select one and only one row.");
+            throw new TorqueException("Failed to select one and only one row.");
         }
         else
         {
@@ -908,11 +936,11 @@
 
 #if ($complexObjectModel)
 
- ## 
+ ##
  ## setup joins
  ##
- #set ( $className = $table.JavaName ) 
- #set ( $countFK = 0 )  
+ #set ( $className = $table.JavaName )
+ #set ( $countFK = 0 )
  #foreach ($dummyFK in $table.ForeignKeys)
       #set ( $countFK = $countFK + 1 )
  #end
@@ -955,15 +983,15 @@
     * actually need in ${table.JavaName}Peer.
     */
     protected static Vector doSelectJoin${joinColumnId}(Criteria c)
-        throws Exception
+        throws TorqueException
     {
     #if ($targetDatabase == "postgresql" && $table.requiresTransactionInPostgres())
          // stuff for postgresql problem.....
          c.setBlobFlag();
-    #end 
+    #end
 
         // Set the correct dbName if it has not been overridden
-        // c.getDbName will return the same object if not set to 
+        // c.getDbName will return the same object if not set to
         // another value so == check is okay and faster
         if ( c.getDbName() == Torque.getDefaultDB() )
         {
@@ -998,10 +1026,10 @@
                     c.add($cup, 1);
                 }
                 else
-                {   
+                {
                     c.add($cup, 0);
                 }
-            }                     
+            }
          }
          #elseif ($col.isBooleanChar())
         // check for conversion from boolean to Y/N
@@ -1015,14 +1043,14 @@
                     c.add($cup, "Y");
                 }
                 else
-                {   
+                {
                     c.add($cup, "N");
                 }
-            }                     
+            }
          }
          #end
      #end
-        
+
         Vector rows = BasePeer.doSelect(c);
         Vector results = new Vector();
 
@@ -1050,7 +1078,7 @@
 #set ($classDecl = "")
             $joinClassName obj2 = ($joinClassName)${joinClassName}Peer
                 .row2Object(row, offset, omClass);
-            
+
             boolean newObject = true;
             for (int j=0; j<results.size(); j++)
             {
@@ -1075,8 +1103,8 @@
         return results;
     }
   #end
- #end 
- #end 
+ #end
+ #end
 
 ## ===========================================================
 
@@ -1107,21 +1135,21 @@
 
 
    /**
-    * selects a collection of $className objects pre-filled with 
+    * selects a collection of $className objects pre-filled with
     * all related objects.
     *
     * This method is protected by default in order to keep the public
     * api reasonable.  You can provide public methods for those you
     * actually need in ${table.JavaName}Peer.
     */
-    protected static Vector doSelectJoinAllExcept${excludeString}(Criteria c) 
-        throws Exception
+    protected static Vector doSelectJoinAllExcept${excludeString}(Criteria c)
+        throws TorqueException
     {
     #if ($targetDatabase == "postgresql" && $table.requiresTransactionInPostgres())
          // stuff for postgresql problem.....
          c.setBlobFlag();
-    #end 
- 
+    #end
+
         // Set the correct dbName if it has not been overridden
         // c.getDbName will return the same object if not set to another value
         // so == check is okay and faster
@@ -1161,10 +1189,10 @@
                     c.add($cup, 1);
                 }
                 else
-                {   
+                {
                     c.add($cup, 0);
                 }
-            }                     
+            }
          }
          #elseif ($col.isBooleanChar())
         // check for conversion from boolean to Y/N
@@ -1178,10 +1206,10 @@
                     c.add($cup, "Y");
                 }
                 else
-                {   
+                {
                     c.add($cup, "N");
                 }
-            }                     
+            }
          }
          #end
      #end
@@ -1241,9 +1269,9 @@
     #set ($classDecl = "")
             $joinClassName obj$index = ($joinClassName)${joinClassName}Peer
                 .row2Object( row, offset$index, omClass);
-            
+
             #if ($index == 2) boolean #end newObject = true;
-            for (int j=0; j<results.size(); j++)    
+            for (int j=0; j<results.size(); j++)
             {
                 $className temp_obj1 = ($className)results.elementAt(j);
                 $joinClassName temp_obj$index = temp_obj1.get${joinString}();
@@ -1269,23 +1297,23 @@
         return results;
     }
  #end
- #end  
+ #end
 #end
 
 ## ------------------------------------------------------------
 
 
 #if (!$table.isAlias())
-    /** 
-     * Returns the TableMap related to this peer.  This method is not 
+    /**
+     * Returns the TableMap related to this peer.  This method is not
      * needed for general use but a specific application could have a
      * need.
      */
     protected static TableMap getTableMap()
-        throws Exception
+        throws TorqueException
     {
         return Torque.getDatabaseMap(DATABASE_NAME).getTable(TABLE_NAME);
-    }     
+    }
 #end ## ends if (!$table.isAlias())
 
 

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: [PATCH] Standardizing OM for throwing TorqueException

Posted by John McNally <jm...@collab.net>.
I tried to apply your patch and it failed due to file changes.  Other
than for readability, this situation is another reason to use unidiff's
as patch can do a better job of adjusting for changes in the file as
there is more context in the patch.  You get a unidiff with the option

cvs diff -u

not sure how you would specify this in wincvs, but it should have a
command line mode, if you can't find the option, you can tell the
difference easily as -u produces diffs with +/- as opposed to >/<.  Use
the latest cvs and I will apply it right away.

john mcnally

Mathieu Frenette wrote:
> 
> What a daunting task, but I did it!
> 
> It's my first involvement in Open Source, CVS, and Torque, so please be
> indulgent. ;-) I did my best with this action item.  Please let me know if I
> did anything wrong, so I can improve it next time.
> 
> I used WinCVS to produce the diff, but I don't know if it's "unidiff"
> compliant, as you mentionned that "unidiff" was preferred.  Also, I left all
> file diffs in the same text file.  Let me know if this poses a problem.
> 
> In addition to the patch file, I included a zip containing all the files
> after modification, just in case you need them.
> 
> Here's my work report:
> 
> *********************************
> 
> * Modified the following files for using TorqueException, and fixed javadoc
> comments:
> 
>     Torque.java
>     BasePeer.java
>     SqlExpression.java
>     Criteria.java
> 
>     MapBuilder.vm
>     Object.vm
>     Peer.vm
> 
> * Decided to leave the IdGenerator interface unchanged for now, because
> changing it to throw TorqueException instead of Exception might break
> people's code that implement this interface.  However, it would not affect
> code that is _using_ this interface.  We should discuss how this will be
> addressed.  If we settle to change it in some way, I can take care of it,
> including Torque classes which implement it.
> 
> * Simplified try/finally clauses (but only when it was in the scope of a
> required modification) from this style:
> 
>     dbCon = null;
>     try
>     {
>       dbCon = Torque.getConnection(dbName);
>       doDelete(criteria, dbCon);
>     }
>     finally
>     {
>       if (dbCon == null)
>           Torque.releaseConnection(dbCon);
>     }
> 
> to this style:
> 
>     dbCon = Torque.getConnection(dbName);
>     try
>     {
>       doDelete(criteria, dbCon);
>     }
>     finally
>     {
>       Torque.releaseConnection(dbCon);
>     }
> 
> Please confirm with me that this doesn't affect the intended semantic.  For
> example, I assumed that if .getConnection() failed, then
> .releaseConnection() doesn't need to be called.
> 
> * Tried to avoid excessive exception wrapping.  For example, in cases where
> SQLException, DataSetException and TorqueException are thrown by a portion
> of code, I explicitly catch the two first individually, and let
> TorqueException fall through.  (I could have caught Exception and wrap it
> into TorqueException, but that would allow TorqueExceptions to be wrapped
> many levels deep, which we don't want).
> 
> * Used the following style of try/catch/finally in order to simplify
> handling of cases where the finally clause may throw exceptions to be
> caught.  This is the cleanest way I know of handling this kind of situation:
> 
>     try
>     {
>         try
>         {
>             // Do something which may throw SQLException
>         }
>         finally
>         {
>             // Clean-up which may throw SQLException
>         }
>     }
>     catch(SQLException e)
>     {
>         throw new TorqueException(e);
>     }
> 
> *********************************
> 
> Comments would be appreciated! :-)
> 
> Looking forward to hearing from you...
> 
> -- Mathieu
> 
>   ------------------------------------------------------------------------
>                                       Name: StdUsageOfTorqueException.patch
>    StdUsageOfTorqueException.patch    Type: unspecified type (application/octet-stream)
>                                   Encoding: quoted-printable
> 
>                        Name: PatchedFiles.zip
>    PatchedFiles.zip    Type: Zip Compressed Data (application/x-zip-compressed)
>                    Encoding: base64
> 
>   ------------------------------------------------------------------------
> --
> To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
> For additional commands, e-mail: <ma...@jakarta.apache.org>

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: [PATCH] Standardizing OM for throwing TorqueException (1/3)

Posted by Daniel Rall <dl...@finemaltcoding.com>.
Here's a version of TorqueException integration (using Mathieu's patch
as a base) which applies against current CVS HEAD.  I had to re-do the
BasePeer patch (which took a long time, damn it ;-).

Dan


Index: java/org/apache/torque/Torque.java
===================================================================
RCS file: /home/cvs/jakarta-turbine-torque/src/java/org/apache/torque/Torque.java,v
retrieving revision 1.43
diff -u -r1.43 Torque.java
--- java/org/apache/torque/Torque.java	6 Feb 2002 15:18:56 -0000	1.43
+++ java/org/apache/torque/Torque.java	26 Feb 2002 18:48:27 -0000
@@ -54,8 +54,7 @@
  * <http://www.apache.org/>.
  */
 
-import java.io.File;
-import java.io.FileInputStream;
+import java.io.*;
 import java.util.HashMap;
 import java.util.Enumeration;
 import java.util.Iterator;
@@ -154,14 +153,16 @@
      * initialize Torque
      *
      * @see org.apache.stratum.lifecycle.Initializable
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      */
-    public void initialize() throws Exception
+    public void initialize() throws TorqueException
     {
         // FIX ME!!
         // duplicated code init(Configuration)
         if (configuration == null)
         {
-            throw new Exception("Torque cannot be initialized without " +
+            throw new TorqueException("Torque cannot be initialized without " +
                 "a valid configuration. Please check the log files " +
                     "for further details.");
         }
@@ -220,8 +221,10 @@
      * configure torque
      *
      * @see org.apache.stratum.lifecycle.Configurable
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      */
-    public void configure(Configuration config) throws NestableException
+    public void configure(Configuration config) throws TorqueException
     {
         configuration = config;
     }
@@ -230,26 +233,37 @@
      * Initialization of Torque with a properties file.
      *
      * @param configFile The absolute path to the configuration file.
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      */
     public static void init(String configFile)
-        throws Exception
+        throws TorqueException
     {
-        Configuration c = (Configuration)new PropertiesConfiguration(configFile);
-        init(c);
+        try
+        {
+            Configuration c = (Configuration)new PropertiesConfiguration(configFile);
+            init(c);
+        }
+        catch (IOException e)
+        {
+            throw new TorqueException(e);
+        }
     }
 
     /**
      * Initialization of Torque with a properties file.
      *
      * @param c The Torque configuration.
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      */
     public static void init(Configuration c)
-        throws Exception
+        throws TorqueException
     {
         Torque.setConfiguration(c);
         if (configuration == null)
         {
-            throw new Exception("Torque cannot be initialized without " +
+            throw new TorqueException("Torque cannot be initialized without " +
                 "a valid configuration. Please check the log files " +
                     "for further details.");
         }
@@ -477,7 +491,7 @@
      * Returns the default database map information.
      *
      * @return A DatabaseMap.
-     * @throws TorqueException Any exceptions caught during procssing will be
+     * @throws TorqueException Any exceptions caught during processing will be
      *         rethrown wrapped into a TorqueException.
      */
     public static DatabaseMap getDatabaseMap()
@@ -493,8 +507,8 @@
      * @param name The name of the database corresponding to the
      * <code>DatabaseMap</code> to retrieve.
      * @return The named <code>DatabaseMap</code>.
-     * @throws TorqueException Any exceptions caught during procssing
-     * will be rethrown wrapped into a <code>TorqueException</code>.
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      */
     public static DatabaseMap getDatabaseMap(String name)
         throws TorqueException
@@ -527,6 +541,8 @@
      *
      * @param name The name of the database to map.
      * @return The desired map.
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      */
     private static final DatabaseMap initDatabaseMap(String name)
         throws TorqueException
@@ -610,7 +626,7 @@
      *         rethrown wrapped into a TorqueException.
      */
     public static DBConnection getConnection()
-        throws Exception
+        throws TorqueException
     {
         return getConnection(getDefaultDB());
     }
@@ -635,10 +651,17 @@
      *         rethrown wrapped into a TorqueException.
      */
     public static DBConnection getConnection(String name)
-        throws Exception
+        throws TorqueException
     {
-        // The getPool method ensures the validity of the returned pool.
-        return getPool(name).getConnection();
+        try
+        {
+            // The getPool method ensures the validity of the returned pool.
+            return getPool(name).getConnection();
+        }
+        catch (Exception e)
+        {
+            throw new TorqueException(e);
+        }
     }
 
     /**
@@ -660,7 +683,7 @@
                                       String url,
                                       String username,
                                       String password)
-        throws Exception
+        throws TorqueException
     {
         ConnectionPool pool = null;
         url = url.trim();
@@ -675,7 +698,14 @@
             pool = (ConnectionPool) pools.get(url + username);
         }
 
-        return pool.getConnection();
+        try
+        {
+            return pool.getConnection();
+        }
+        catch (Exception e)
+        {
+            throw new TorqueException(e);
+        }
     }
 
     /**
@@ -684,17 +714,23 @@
      *
      * @throws TorqueException Any exceptions caught during processing will be
      *         rethrown wrapped into a TorqueException.
-     * @exception Exception A generic exception.
      */
     public static void releaseConnection(DBConnection dbconn)
-        throws Exception
+        throws TorqueException
     {
         if ( dbconn != null )
         {
             ConnectionPool pool = dbconn.getPool();
             if ( pools.containsValue( pool ) )
             {
-                pool.releaseConnection( dbconn );
+                try
+                {
+                    pool.releaseConnection( dbconn );
+                }
+                catch (Exception e)
+                {
+                    throw new TorqueException(e);
+                }
             }
         }
     }
@@ -708,7 +744,7 @@
      * @param username The name of the database user.
      * @param password The password of the database user.
      *
-     * @throws Exception Any exceptions caught during processing will be
+     * @throws TorqueException Any exceptions caught during processing will be
      *         rethrown wrapped into a TorqueException.
      */
     public static void registerPool( String name,
@@ -716,7 +752,7 @@
                               String url,
                               String username,
                               String password )
-        throws Exception
+        throws TorqueException
     {
         /**
          * Added so that the configuration file can define maxConnections &
@@ -746,7 +782,8 @@
      * @param url The URL of the database to use.
      * @param username The name of the database user.
      * @param password The password of the database user.
-     * @exception Exception A generic exception.
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      */
     public static void registerPool( String name,
                               String driver,
@@ -757,7 +794,7 @@
                               long expiryTime,
                               long maxConnectionAttempts,
                               long connectionWaitTimeout)
-        throws Exception
+        throws TorqueException
     {
 
         // Quick (non-sync) check for the pool we want.
@@ -795,7 +832,7 @@
      *         rethrown wrapped into a TorqueException.
      */
     public static DB getDB()
-        throws Exception
+        throws TorqueException
     {
         return getDB(getDefaultDB());
     }
@@ -809,9 +846,16 @@
      *         rethrown wrapped into a TorqueException.
      */
     public static DB getDB(String name)
-        throws Exception
+        throws TorqueException
     {
-        return getPool(name).getDB();
+        try
+        {
+            return getPool(name).getDB();
+        }
+        catch (Exception e)
+        {
+            throw new TorqueException(e);
+        }
     }
 
     ///////////////////////////////////////////////////////////////////////////
@@ -820,11 +864,12 @@
      * This method returns the default pool.
      *
      * @return The default pool.
-     * @exception Exception A generic exception.
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      * @see #getPool(String name)
      */
     private static ConnectionPool getPool()
-        throws Exception
+        throws TorqueException
     {
         return getPool(getDefaultDB());
     }
@@ -838,11 +883,11 @@
      *
      * @param name The name of the pool to get.
      * @return     The requested pool.
-     *
-     * @exception Exception A generic exception.
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      */
     private static ConnectionPool getPool(String name)
-        throws Exception
+        throws TorqueException
     {
         if (name == null)
         {
Index: java/org/apache/torque/util/BasePeer.java
===================================================================
RCS file: /home/cvs/jakarta-turbine-torque/src/java/org/apache/torque/util/BasePeer.java,v
retrieving revision 1.25
diff -u -r1.25 BasePeer.java
--- java/org/apache/torque/util/BasePeer.java	23 Feb 2002 05:49:20 -0000	1.25
+++ java/org/apache/torque/util/BasePeer.java	26 Feb 2002 18:48:33 -0000
@@ -61,9 +61,11 @@
 import com.workingdogs.village.Record;
 import com.workingdogs.village.Schema;
 import com.workingdogs.village.TableDataSet;
+
 import java.io.BufferedOutputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.FilterOutputStream;
+import java.io.IOException;
 import java.io.ObjectOutputStream;
 import java.io.Serializable;
 import java.math.BigDecimal;
@@ -71,6 +73,7 @@
 import java.sql.DatabaseMetaData;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
+import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.Date;
 import java.util.Enumeration;
@@ -78,6 +81,8 @@
 import java.util.Iterator;
 import java.util.List;
 import java.util.Vector;
+
+import org.apache.torque.TorqueException;
 import org.apache.torque.om.NumberKey;
 import org.apache.torque.om.ObjectKey;
 import org.apache.torque.om.SimpleKey;
@@ -94,11 +99,12 @@
 import org.apache.torque.util.Query;
 import org.apache.torque.util.SqlExpression;
 
-//!! no good.
-import org.apache.commons.util.StringStack;
-import org.apache.torque.TorqueException;
 import org.apache.log4j.Category;
 
+// StringStack has been moved from util to collections (dlr)
+import org.apache.commons.util.StringStack;
+//import org.apache.commons.collections.StringStack;
+
 /**
  * This is the base class for all Peer classes in the system.  Peer
  * classes are responsible for isolating all of the database access
@@ -141,10 +147,10 @@
      *
      * @param hash The Hashtable to convert.
      * @return A byte[] with the converted Hashtable.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static byte[] hashtableToByteArray( Hashtable hash )
-        throws Exception
+        throws TorqueException
     {
         Hashtable saveData = new Hashtable(hash.size());
         String key = null;
@@ -175,11 +181,44 @@
             bos.flush();
             byteArray = baos.toByteArray();
         }
+        catch (Exception e)
+        {
+            throw new TorqueException(e);
+        }
         finally
         {
-            if (out != null) out.close();
-            if (bos != null) bos.close();
-            if (baos != null) baos.close();
+            if (out != null)
+            {
+                try
+                {
+                    out.close();
+                }
+                catch (IOException ignored)
+                {
+                }
+            }
+
+            if (bos != null)
+            {
+                try
+                {
+                    bos.close();
+                }
+                catch (IOException ignored)
+                {
+                }
+            }
+
+            if (baos != null)
+            {
+                try
+                {
+                    baos.close();
+                }
+                catch (IOException ignored)
+                {
+                }
+            }
         }
         return byteArray;
     }
@@ -318,15 +357,22 @@
      *
      * @param dbName Name of database.
      * @return The DBConnection for the transaction.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static DBConnection beginTransaction(String dbName)
-        throws Exception
+        throws TorqueException
     {
         DBConnection dbCon = Torque.getConnection( dbName );
-        if ( dbCon.getConnection().getMetaData().supportsTransactions() )
+        try
         {
-            dbCon.setAutoCommit(false);
+            if ( dbCon.getConnection().getMetaData().supportsTransactions() )
+            {
+                dbCon.setAutoCommit(false);
+            }
+        }
+        catch (SQLException e)
+        {
+            throw new TorqueException(e);
         }
 
         return dbCon;
@@ -338,10 +384,10 @@
      * transactions, it only returns the connection.
      *
      * @param dbCon The DBConnection for the transaction.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static void commitTransaction(DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
         try
         {
@@ -351,6 +397,10 @@
                 dbCon.setAutoCommit(true);
             }
         }
+        catch (SQLException e)
+        {
+            throw new TorqueException(e);
+        }
         finally
         {
             // Release the connection to the pool.
@@ -365,10 +415,10 @@
      * connection.
      *
      * @param dbCon The DBConnection for the transaction.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static void rollBackTransaction(DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
         try
         {
@@ -383,6 +433,10 @@
                                + " database did not allow the operation to be rolled back.");
             }
         }
+        catch (SQLException e)
+        {
+            throw new TorqueException(e);
+        }
         finally
         {
             // Release the connection to the pool.
@@ -400,34 +454,46 @@
      * @param table The table to delete records from.
      * @param column The column in the where clause.
      * @param value The value of the column.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static void deleteAll( DBConnection dbCon,
                                   String table,
                                   String column,
                                   int value )
-        throws Exception
+        throws TorqueException
     {
-        Connection conn = dbCon.getConnection();
         Statement statement = null;
-
         try
         {
+            Connection conn = dbCon.getConnection();
             statement = conn.createStatement();
 
             StringBuffer query = new StringBuffer();
             query.append( "DELETE FROM " )
-            .append( table )
-            .append( " WHERE " )
-            .append( column )
-            .append( " = " )
-            .append( value );
+                .append( table )
+                .append( " WHERE " )
+                .append( column )
+                .append( " = " )
+                .append( value );
 
             statement.executeUpdate( query.toString() );
         }
+        catch (SQLException e)
+        {
+            throw new TorqueException(e);
+        }
         finally
         {
-            if (statement != null) statement.close();
+            if (statement != null)
+            {
+                try
+                {
+                    statement.close();
+                }
+                catch (SQLException ignored)
+                {
+                }
+            }
         }
     }
 
@@ -440,12 +506,12 @@
      * @param table The table to delete records from.
      * @param column The column in the where clause.
      * @param value The value of the column.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static void deleteAll( String table,
                                   String column,
                                   int value )
-        throws Exception
+        throws TorqueException
     {
         DBConnection dbCon = null;
         try
@@ -466,10 +532,10 @@
      * Criteria.
      *
      * @param criteria The criteria to use.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static void doDelete(Criteria criteria)
-        throws Exception
+        throws TorqueException
     {
         DBConnection dbCon = null;
         String dbName = criteria.getDbName();
@@ -510,24 +576,32 @@
      *
      * @param criteria The criteria to use.
      * @param dbCon A DBConnection.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static void doDelete(Criteria criteria,
                                 DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
         DB db = Torque.getDB( criteria.getDbName() );
         DatabaseMap dbMap = Torque.getDatabaseMap( criteria.getDbName() );
-        Connection connection = dbCon.getConnection();
+        Connection connection = null;
+        try
+        {
+            connection = dbCon.getConnection();
+        }
+        catch (SQLException e)
+        {
+            throw new TorqueException(e);
+        }
 
         // Set up a list of required tables and add extra entries to
         // criteria if directed to delete all related records.
         // StringStack.add() only adds element if it is unique.
         StringStack tables = new StringStack();
-        Enumeration e = criteria.keys();
-        while(e.hasMoreElements())
+        Enumeration enum = criteria.keys();
+        while (enum.hasMoreElements())
         {
-            String key = (String)e.nextElement();
+            String key = (String) enum.nextElement();
             Criteria.Criterion c = criteria.getCriterion(key);
             String[] tableNames = c.getAllTables();
             for (int i=0; i<tableNames.length; i++)
@@ -627,9 +701,22 @@
                     rec.save();
                 }
             }
+            catch (Exception e)
+            {
+                throw new TorqueException(e);
+            }
             finally
             {
-                if (tds != null) tds.close();
+                if (tds != null)
+                {
+                    try
+                    {
+                        tds.close();
+                    }
+                    catch (Exception ignored)
+                    {
+                    }
+                }
             }
         }
     }
@@ -663,10 +750,10 @@
      * @return An Object which is the id of the row that was inserted
      * (if the table has a primary key) or null (if the table does not
      * have a primary key).
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static ObjectKey doInsert(Criteria criteria)
-        throws Exception
+        throws TorqueException
     {
         DBConnection dbCon = null;
         ObjectKey id = null;
@@ -732,11 +819,11 @@
      * @return An Object which is the id of the row that was inserted
      * (if the table has a primary key) or null (if the table does not
      * have a primary key).
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static ObjectKey doInsert(Criteria criteria,
                                      DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
         SimpleKey id = null;
 
@@ -750,7 +837,7 @@
         }
         else
         {
-            throw new Exception("Database insert attempted without " + 
+            throw new TorqueException("Database insert attempted without " + 
                 "anything specified to insert");
         }
         
@@ -773,23 +860,30 @@
         {
             if (keyGen == null)
             {
-                throw new Exception("IdGenerator for table '" + tableName + 
-                                    "' is null");
+                throw new TorqueException("IdGenerator for table '" +
+                                          tableName + "' is null");
             }
             // If the keyMethod is SEQUENCE or IDBROKERTABLE, get the id
             // before the insert.
 
             if (keyGen.isPriorToInsert())
             {
-                if ( pk.getType() instanceof Number )
+                try
                 {
-                    id = new NumberKey( keyGen
-                        .getIdAsBigDecimal(dbCon.getConnection(), keyInfo) );
+                    if ( pk.getType() instanceof Number )
+                    {
+                        id = new NumberKey(keyGen.getIdAsBigDecimal
+                                           (dbCon.getConnection(), keyInfo));
+                    }
+                    else
+                    {
+                        id = new StringKey(keyGen.getIdAsString
+                                           (dbCon.getConnection(), keyInfo));
+                    }
                 }
-                else
+                catch (Exception e)
                 {
-                    id = new StringKey( keyGen
-                        .getIdAsString(dbCon.getConnection(), keyInfo) );
+                    throw new TorqueException(e);
                 }
                 criteria.add( pk.getFullyQualifiedName(), id );
             }
@@ -803,27 +897,45 @@
             Record rec = tds.addRecord();
             BasePeer.insertOrUpdateRecord(rec, tableName, criteria);
         }
+        catch (Exception e)
+        {
+            throw new TorqueException(e);
+        }
         finally
         {
             if (tds != null)
             {
-                tds.close();
+                try
+                {
+                    tds.close();
+                }
+                catch (Exception e)
+                {
+                    throw new TorqueException(e);
+                }
             }
         }
 
         // If the primary key column is auto-incremented, get the id
         // now.
-        if ((keyGen != null) && (keyGen.isPostInsert()))
+        if (keyGen != null && keyGen.isPostInsert())
         {
-            if ( pk.getType() instanceof Number )
+            try
             {
-                id = new NumberKey( keyGen
-                    .getIdAsBigDecimal(dbCon.getConnection(), keyInfo) );
+                if ( pk.getType() instanceof Number )
+                {
+                id = new NumberKey(keyGen.getIdAsBigDecimal
+                                   (dbCon.getConnection(), keyInfo));
+                }
+                else
+                {
+                    id = new StringKey(keyGen.getIdAsString
+                                       (dbCon.getConnection(), keyInfo));
+                }
             }
-            else
+            catch (Exception e)
             {
-                id = new StringKey( keyGen
-                    .getIdAsString(dbCon.getConnection(), keyInfo) );
+                throw new TorqueException(e);
             }
         }
 
@@ -837,12 +949,12 @@
      * @param rec A Record.
      * @param tableName Name of table.
      * @param criteria A Criteria.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     private static void insertOrUpdateRecord(Record rec,
                                              String tableName,
                                              Criteria criteria)
-        throws Exception
+        throws TorqueException
     {
         DatabaseMap dbMap = Torque.getDatabaseMap( criteria.getDbName() );
 
@@ -862,64 +974,71 @@
                 {
                     obj = ((SimpleKey)obj).getValue();
                 }
-                if (obj == null)
-                {
-                    rec.setValueNull(colMap.getColumnName());
-                }
-                else if ( obj instanceof String )
-                {
-                    rec.setValue( colMap.getColumnName(),
-                                  (String)obj );
-                }
-                else if ( obj instanceof Integer)
-                {
-                    rec.setValue( colMap.getColumnName(),
-                                  criteria.getInt(key) );
-                }
-                else if ( obj instanceof BigDecimal)
-                {
-                    rec.setValue( colMap.getColumnName(),
-                                  (BigDecimal)obj );
-                }
-                else if ( obj instanceof Boolean)
-                {
-                    rec.setValue( colMap.getColumnName(),
-                                   criteria.getBoolean(key) ? 1 : 0);
-                }
-                else if ( obj instanceof java.util.Date)
-                {
-                    rec.setValue( colMap.getColumnName(),
-                                  (java.util.Date)obj );
-                }
-                else if ( obj instanceof Float)
-                {
-                    rec.setValue( colMap.getColumnName(),
-                                  criteria.getFloat(key) );
-                }
-                else if ( obj instanceof Double)
-                {
-                    rec.setValue( colMap.getColumnName(),
-                                  criteria.getDouble(key) );
-                }
-                else if ( obj instanceof Byte)
-                {
-                    rec.setValue( colMap.getColumnName(),
-                                  ((Byte) obj).byteValue() );
-                }
-                else if ( obj instanceof Long)
+                try
                 {
-                    rec.setValue( colMap.getColumnName(),
-                                  criteria.getLong(key) );
-                }
-                else if ( obj instanceof Hashtable )
-                {
-                    rec.setValue( colMap.getColumnName(),
-                                  hashtableToByteArray( (Hashtable)obj ) );
+                    if (obj == null)
+                    {
+                        rec.setValueNull(colMap.getColumnName());
+                    }
+                    else if ( obj instanceof String )
+                    {
+                        rec.setValue( colMap.getColumnName(),
+                                      (String)obj );
+                    }
+                    else if ( obj instanceof Integer)
+                    {
+                        rec.setValue( colMap.getColumnName(),
+                                      criteria.getInt(key) );
+                    }
+                    else if ( obj instanceof BigDecimal)
+                    {
+                        rec.setValue( colMap.getColumnName(),
+                                      (BigDecimal)obj );
+                    }
+                    else if ( obj instanceof Boolean)
+                    {
+                        rec.setValue( colMap.getColumnName(),
+                                      criteria.getBoolean(key) ? 1 : 0);
+                    }
+                    else if ( obj instanceof java.util.Date)
+                    {
+                        rec.setValue( colMap.getColumnName(),
+                                      (java.util.Date)obj );
+                    }
+                    else if ( obj instanceof Float)
+                    {
+                        rec.setValue( colMap.getColumnName(),
+                                      criteria.getFloat(key) );
+                    }
+                    else if ( obj instanceof Double)
+                    {
+                        rec.setValue( colMap.getColumnName(),
+                                      criteria.getDouble(key) );
+                    }
+                    else if ( obj instanceof Byte)
+                    {
+                        rec.setValue( colMap.getColumnName(),
+                                      ((Byte) obj).byteValue() );
+                    }
+                    else if ( obj instanceof Long)
+                    {
+                        rec.setValue( colMap.getColumnName(),
+                                      criteria.getLong(key) );
+                    }
+                    else if ( obj instanceof Hashtable )
+                    {
+                        rec.setValue( colMap.getColumnName(),
+                                      hashtableToByteArray( (Hashtable)obj ) );
+                    }
+                    else if ( obj instanceof byte[])
+                    {
+                        rec.setValue( colMap.getColumnName(),
+                                      (byte[])obj);
+                    }
                 }
-                else if ( obj instanceof byte[])
+                catch (Exception e)
                 {
-                    rec.setValue( colMap.getColumnName(),
-                                  (byte[])obj);
+                    throw new TorqueException(e);
                 }
                 shouldSave = true;
              }
@@ -927,11 +1046,18 @@
 
         if ( shouldSave )
         {
-            rec.save();
+            try
+            {
+                rec.save();
+            }
+            catch (Exception e)
+            {
+                throw new TorqueException(e);
+            }
         }
         else
         {
-           throw new Exception ( "BasePeer.doInsert() - Nothing to insert" );
+           throw new TorqueException("No changes to save");
         }
     }
 
@@ -942,7 +1068,7 @@
      * @exception Exception Trouble creating the query string.
      */
     public static String createQueryString( Criteria criteria )
-        throws Exception
+        throws TorqueException
     {
         Query query = new Query();
         DB db = Torque.getDB( criteria.getDbName() );
@@ -970,7 +1096,7 @@
             String columnName = select.get(i);
             if (columnName.indexOf('.') == -1)
             {
-                throw getMalformedColumnNameException("select", columnName);
+                throwMalformedColumnNameException("select", columnName);
             }
             String tableName = null;
             selectClause.add(columnName);
@@ -1063,11 +1189,11 @@
                 String join2 = (String)criteria.getJoinR().get(i);
                 if (join1.indexOf('.') == -1)
                 {
-                    throw getMalformedColumnNameException("join",join1);
+                    throwMalformedColumnNameException("join",join1);
                 }
                 if (join2.indexOf('.') == -1)
                 {
-                    throw getMalformedColumnNameException("join",join2);
+                    throwMalformedColumnNameException("join",join2);
                 }
 
                 String tableName = join1.substring(0, join1.indexOf('.'));
@@ -1122,7 +1248,7 @@
                 String orderByColumn = orderBy.get(i);
                 if (orderByColumn.indexOf('.') == -1)
                 {
-                    throw getMalformedColumnNameException("order by",orderByColumn);
+                    throwMalformedColumnNameException("order by",orderByColumn);
                 }
                 String table = orderByColumn.substring(0,orderByColumn.indexOf('.') );
                 // See if there's a space (between the column list and sort
@@ -1198,10 +1324,10 @@
      *
      * @param criteria A Criteria.
      * @return Vector of Record objects.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static Vector doSelect(Criteria criteria)
-        throws Exception
+        throws TorqueException
     {
         Vector results = null;
         if (criteria.containsObjectColumn(criteria.getDbName()))
@@ -1217,7 +1343,7 @@
             {
                 // make sure to return connection
                 rollBackTransaction(dbCon);

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: [PATCH] Standardizing OM for throwing TorqueException (2/3)

Posted by Daniel Rall <dl...@finemaltcoding.com>.
-                throw e;
+                throw new TorqueException(e);
             }
         }
         else
@@ -1235,11 +1361,11 @@
      * @param criteria A Criteria.
      * @param dbCon A DBConnection.
      * @return Vector of Record objects.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static Vector doSelect(Criteria criteria,
                                   DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
         return executeQuery( createQueryString(criteria),
                              criteria.isSingleRecord(), dbCon );
@@ -1252,10 +1378,10 @@
      *
      * @param queryString A String with the sql statement to execute.
      * @return Vector of Record objects.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static Vector executeQuery(String queryString)
-        throws Exception
+        throws TorqueException
     {
         return executeQuery(queryString, Torque.getDefaultDB(), false);
     }
@@ -1268,11 +1394,11 @@
      * @param queryString A String with the sql statement to execute.
      * @param dbName The database to connect to.
      * @return Vector of Record objects.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static Vector executeQuery(String queryString,
                                       String dbName)
-        throws Exception
+        throws TorqueException
     {
         return executeQuery(queryString, dbName, false);
     }
@@ -1285,12 +1411,12 @@
      * @param singleRecord Whether or not we want to select only a
      * single record.
      * @return Vector of Record objects.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static Vector executeQuery(String queryString,
                                       String dbName,
                                       boolean singleRecord)
-        throws Exception
+        throws TorqueException
     {
         return executeQuery(queryString, 0, -1, dbName, singleRecord);
     }
@@ -1304,12 +1430,12 @@
      * single record.
      * @param dbCon A DBConnection.
      * @return Vector of Record objects.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static Vector executeQuery(String queryString,
                                       boolean singleRecord,
                                       DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
         return executeQuery(queryString, 0, -1, singleRecord, dbCon);
     }
@@ -1325,14 +1451,14 @@
      * @param singleRecord Whether or not we want to select only a
      * single record.
      * @return Vector of Record objects.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static Vector executeQuery(String queryString,
                                       int start,
                                       int numberOfResults,
                                       String dbName,
                                       boolean singleRecord)
-        throws Exception
+        throws TorqueException
     {
         DBConnection db = null;
         Vector results = null;
@@ -1362,16 +1488,24 @@
      * single record.
      * @param dbCon A DBConnection.
      * @return Vector of Record objects.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static Vector executeQuery(String queryString,
                                       int start,
                                       int numberOfResults,
                                       boolean singleRecord,
                                       DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
-        Connection connection = dbCon.getConnection();
+        Connection connection = null;
+        try
+        {
+            connection = dbCon.getConnection();
+        }
+        catch (SQLException e)
+        {
+            throw new TorqueException(e);
+        }
 
         QueryDataSet qds = null;
         Vector results = new Vector();
@@ -1385,9 +1519,22 @@
             results = getSelectResults( qds, start, numberOfResults,
                                         singleRecord);
         }
+        catch (Exception e)
+        {
+            throw new TorqueException(e);
+        }
         finally
         {
-            if (qds != null) qds.close();
+            if (qds != null)
+            {
+                try
+                {
+                    qds.close();
+                }
+                catch (Exception ignored)
+                {
+                }
+            }
         }
         return results;
     }
@@ -1399,10 +1546,10 @@
      *
      * @param qds A QueryDataSet.
      * @return Vector of Record objects.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static Vector getSelectResults( QueryDataSet qds )
-        throws Exception
+        throws TorqueException
     {
         return getSelectResults( qds, 0, -1, false);
     }
@@ -1414,11 +1561,11 @@
      * @param qds A QueryDataSet.
      * @param singleRecord Whether or not we want to select only a
      * single record.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static Vector getSelectResults( QueryDataSet qds,
                                            boolean singleRecord )
-        throws Exception
+        throws TorqueException
     {
         return getSelectResults(qds, 0, -1, singleRecord);
     }
@@ -1432,12 +1579,12 @@
      * @param numberOfResults The number of results to return.
      * @param singleRecord Whether or not we want to select only a
      * single record.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static Vector getSelectResults( QueryDataSet qds,
                                            int numberOfResults,
                                            boolean singleRecord )
-        throws Exception
+        throws TorqueException
     {
         Vector results = null;
         if (numberOfResults != 0)
@@ -1457,35 +1604,42 @@
      * @param numberOfResults The number of results to return.
      * @param singleRecord Whether or not we want to select only a
      * single record.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static Vector getSelectResults( QueryDataSet qds,
                                            int start,
                                            int numberOfResults,
                                            boolean singleRecord )
-        throws Exception
+        throws TorqueException
     {
         Vector results;
-        if ( numberOfResults <= 0 )
-        {
-            results = new Vector();
-            qds.fetchRecords();
-        }
-        else
-        {
-            results = new Vector(numberOfResults);
-            qds.fetchRecords(start, numberOfResults);
-        }
-        if ( qds.size() > 1 && singleRecord )
+        try
         {
-            handleMultipleRecords(qds);
-        }
+            if ( numberOfResults <= 0 )
+            {
+                results = new Vector();
+                qds.fetchRecords();
+            }
+            else
+            {
+                results = new Vector(numberOfResults);
+                qds.fetchRecords(start, numberOfResults);
+            }
+            if ( qds.size() > 1 && singleRecord )
+            {
+                handleMultipleRecords(qds);
+            }
 
-        // Return a Vector of Record objects.
-        for ( int i=0; i<qds.size(); i++ )
+            // Return a Vector of Record objects.
+            for ( int i=0; i<qds.size(); i++ )
+            {
+                Record rec = qds.getRecord(i);
+                results.addElement(rec);
+            }
+        }
+        catch (Exception e)
         {
-            Record rec = qds.getRecord(i);
-            results.addElement(rec);
+            throw new TorqueException(e);
         }
         return results;
     }
@@ -1497,10 +1651,10 @@
      * @param criteria A Criteria.
      * @return ColumnMap if the Criteria object contains a primary
      * key, or null if it doesn't.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     private static ColumnMap getPrimaryKey(Criteria criteria)
-        throws Exception
+        throws TorqueException
     {
         // Assume all the keys are for the same table.
         String key = (String)criteria.keys().nextElement();
@@ -1512,9 +1666,13 @@
         {
             DatabaseMap dbMap = Torque.getDatabaseMap(criteria.getDbName());
             if (dbMap == null)
-                throw new Exception ("dbMap is null");
+            {
+                throw new TorqueException("dbMap is null");
+            }
             if (dbMap.getTable(table) == null)
-                throw new Exception ("dbMap.getTable() is null");
+            {
+                throw new TorqueException("dbMap.getTable() is null");
+            }
 
             ColumnMap[] columns = dbMap.getTable(table).getColumns();
 
@@ -1551,10 +1709,10 @@
      *
      * @param updateValues A Criteria object containing values used in
      * set clause.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static void doUpdate(Criteria updateValues)
-        throws Exception
+        throws TorqueException
     {
         boolean doTransaction =
             updateValues.containsObjectColumn(updateValues.getDbName());
@@ -1609,11 +1767,11 @@
      * @param updateValues A Criteria object containing values used in
      * set clause.
      * @param dbCon A DBConnection.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static void doUpdate(Criteria updateValues,
                                 DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
         ColumnMap pk = getPrimaryKey(updateValues);
         Criteria selectCriteria = null;
@@ -1627,7 +1785,7 @@
         }
         else
         {
-            throw new Exception("BasePeer.doUpdate(criteria) - no PK specified");
+            throw new TorqueException("No PK specified for database update");
         }
 
         doUpdate( selectCriteria, updateValues, dbCon );
@@ -1650,11 +1808,11 @@
      * in where clause.
      * @param updateValues A Criteria object containing values used in
      * set clause.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static void doUpdate(Criteria selectCriteria,
                                 Criteria updateValues)
-        throws Exception
+        throws TorqueException
     {
         boolean doTransaction =
             updateValues.containsObjectColumn(selectCriteria.getDbName());
@@ -1704,25 +1862,34 @@
      * @param updateValues A Criteria object containing values used in
      * set clause.
      * @param dbCon A DBConnection.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static void doUpdate(Criteria selectCriteria,
                                 Criteria updateValues,
                                 DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
         DB db = Torque.getDB( selectCriteria.getDbName() );
         DatabaseMap dbMap =
             Torque.getDatabaseMap( selectCriteria.getDbName() );
-        Connection connection = dbCon.getConnection();
+        Connection connection = null;
+        try
+        {
+            connection = dbCon.getConnection();
+        }
+        catch (SQLException e)
+        {
+            throw new TorqueException(e);
+        }
 
         // Set up a list of required tables.  StringStack.add()
         // only adds element if it is unique.
         StringStack tables = new StringStack();
-        Enumeration e = selectCriteria.keys();
-        while(e.hasMoreElements())
+        Enumeration enum = selectCriteria.keys();
+        while (enum.hasMoreElements())
         {
-            tables.add(selectCriteria.getTableName( (String)e.nextElement() ));
+            tables.add( selectCriteria.getTableName
+                        ((String) enum.nextElement()) );
         }
 
         for (int i=0; i<tables.size(); i++)
@@ -1779,11 +1946,22 @@
                         .insertOrUpdateRecord(rec, tables.get(i), updateValues);
                 }
             }
+            catch (Exception e)
+            {
+                throw new TorqueException(e);
+            }
             finally
             {
                 if (tds != null)
                 {
-                    tds.close();
+                    try
+                    {
+                        tds.close();
+                    }
+                    catch (Exception e)
+                    {
+                        throw new TorqueException(e);
+                    }
                 }
             }
         }
@@ -1796,10 +1974,10 @@
      *
      * @param stmt A String with the sql statement to execute.
      * @return The number of rows affected.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static int executeStatement(String stmt)
-        throws Exception
+        throws TorqueException
     {
         return executeStatement(stmt, Torque.getDefaultDB());
     }
@@ -1815,7 +1993,7 @@
      * @exception Exception, a generic exception.  */
     public static int executeStatement(String stmt,
                                        String dbName)
-        throws Exception
+        throws TorqueException
     {
         DBConnection db = null;
         int rowCount = -1;
@@ -1842,26 +2020,45 @@
      * @param stmt A String with the sql statement to execute.
      * @param dbCon A DBConnection.
      * @return The number of rows affected.
-     * @exception Exception, a generic exception.
+     * @exception TorqueException
      */
     public static int executeStatement(String stmt,
                                        DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
-        Connection con = dbCon.getConnection();
-        Statement statement = null;
         int rowCount = -1;
+        Statement statement = null;
+        Connection con = null;
+        try
+        {
+            dbCon.getConnection();
+        }
+        catch (SQLException e)
+        {
+            throw new TorqueException(e);
+        }
 
         try
         {
             statement = con.createStatement();
             rowCount = statement.executeUpdate( stmt );
         }
+        catch (SQLException e)
+        {
+            throw new TorqueException(e);
+        }
         finally
         {
             if (statement != null)
             {
-                statement.close();
+                try
+                {
+                    statement.close();
+                }
+                catch (SQLException e)
+                {
+                    throw new TorqueException(e);
+                }
             }
         }
         return rowCount;
@@ -1879,17 +2076,17 @@
      * @exception Exception Couldn't handle multiple records.
      */
     protected static void handleMultipleRecords(DataSet ds)
-        throws Exception
+        throws TorqueException
     {
-        throw new Exception(
-            "Criteria expected single Record and Multiple Records were selected.");
+        throw new TorqueException("Criteria expected single Record and " +
+                                  "Multiple Records were selected");
     }
 
     /**
      * @deprecated Use the better-named handleMultipleRecords() instead.
      */
     protected static void handleMultiple(DataSet ds)
-        throws Exception
+        throws TorqueException
     {
         handleMultipleRecords(ds);
     }
@@ -1903,7 +2100,7 @@
      *
      */
     public static MapBuilder getMapBuilder()
-        throws Exception
+        throws TorqueException
     {
         return getMapBuilder(DEFAULT_MAP_BUILDER.trim());
     }
@@ -1989,7 +2186,7 @@
      * @exception Exception Error performing database query.
      */
     public static Vector doPSSelect(Criteria criteria, DBConnection dbCon)
-        throws Exception
+        throws TorqueException
     {
         Vector v = null;
 
@@ -2030,11 +2227,22 @@
                 }
             }
         }
+        catch (Exception e)
+        {
+            throw new TorqueException(e);
+        }
         finally
         {
             if (stmt != null)
             {
-                stmt.close();
+                try
+                {
+                    stmt.close();
+                }
+                catch (SQLException e)
+                {
+                    throw new TorqueException(e);
+                }
             }
         }
 
@@ -2070,7 +2278,7 @@
     public static void createPreparedStatement(Criteria criteria,
                                                StringBuffer queryString,
                                                List params)
-        throws Exception
+        throws TorqueException
     {
         DB db = Torque.getDB( criteria.getDbName() );
         DatabaseMap dbMap = Torque.getDatabaseMap( criteria.getDbName() );
@@ -2104,7 +2312,7 @@
             String columnName = select.get(i);
             if (columnName.indexOf('.') == -1)
             {
-                throw getMalformedColumnNameException("select", columnName);
+                throwMalformedColumnNameException("select", columnName);
             }
             String tableName = null;
             selectClause.add(columnName);
@@ -2194,11 +2402,11 @@
                 String join2 = (String)criteria.getJoinR().get(i);
                 if (join1.indexOf('.') == -1)
                 {
-                    throw getMalformedColumnNameException("join",join1);
+                    throwMalformedColumnNameException("join",join1);
                 }
                 if (join2.indexOf('.') == -1)
                 {
-                    throw getMalformedColumnNameException("join",join2);
+                    throwMalformedColumnNameException("join",join2);
                 }
 
                 String tableName = join1.substring(0, join1.indexOf('.'));
@@ -2253,7 +2461,7 @@
                 String orderByColumn = orderBy.get(i);
                 if (orderByColumn.indexOf('.') == -1)
                 {
-                    throw getMalformedColumnNameException("order by",orderByColumn);
+                    throwMalformedColumnNameException("order by",orderByColumn);
                 }
                 String table = orderByColumn.substring(0,orderByColumn.indexOf('.') );
                 // See if there's a space (between the column list and sort
@@ -2324,23 +2532,23 @@
     }
 
     /**
-     * return an Exception with the malformed column name error message.
-     * The error message looks like this:<p>
+     * Throws a TorqueException with the malformed column name error
+     * message.  The error message looks like this:<p>
      *
      * <code>
-     *     malformed column name in Criteria [criteriaPhrase]:
+     *     Malformed column name in Criteria [criteriaPhrase]:
      *     '[columnName]' is not of the form 'table.column'
      * </code>
      *
      * @param criteriaPhrase a String, one of "select", "join", or "order by"
      * @param columnName a String containing the offending column name
      */
-    private static Exception getMalformedColumnNameException(String criteriaPhrase,
-                                                             String columnName)
-    {
-        return new Exception("malformed column name in Criteria "
-                             + criteriaPhrase + ": '"
-                             + columnName
-                             + "' is not of the form 'table.column'");
+    private static void throwMalformedColumnNameException
+        (String criteriaPhrase, String columnName)
+        throws TorqueException
+    {
+        throw new TorqueException("Malformed column name in Criteria " +
+                                  criteriaPhrase + ": '" + columnName +
+                                  "' is not of the form 'table.column'");
     }
 }
Index: java/org/apache/torque/util/Criteria.java
===================================================================
RCS file: /home/cvs/jakarta-turbine-torque/src/java/org/apache/torque/util/Criteria.java,v
retrieving revision 1.10
diff -u -r1.10 Criteria.java
--- java/org/apache/torque/util/Criteria.java	12 Feb 2002 20:24:47 -0000	1.10
+++ java/org/apache/torque/util/Criteria.java	26 Feb 2002 18:48:40 -0000
@@ -69,6 +69,7 @@
 import java.util.Set;
 import java.util.Vector;
 import org.apache.torque.Torque;
+import org.apache.torque.TorqueException;
 import org.apache.torque.adapter.DB;
 import org.apache.torque.map.DatabaseMap;
 import org.apache.torque.map.TableMap;
@@ -382,9 +383,10 @@
      * Object column.
      *
      * @return A boolean.
-     * @exception Exception, a generic exception.
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      */
-    public boolean containsObjectColumn() throws Exception
+    public boolean containsObjectColumn() throws TorqueException
     {
         return containsObjectColumn(dbName);
     }
@@ -395,10 +397,11 @@
      *
      * @param databaseMapName A String.
      * @return A boolean.
-     * @exception Exception, a generic exception.
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      */
     public boolean containsObjectColumn(String databaseMapName)
-        throws Exception
+        throws TorqueException
     {
         // Peer or application may have noted the existence of a blob
         // so we can save the lookup.
Index: java/org/apache/torque/util/SqlExpression.java
===================================================================
RCS file: /home/cvs/jakarta-turbine-torque/src/java/org/apache/torque/util/SqlExpression.java,v
retrieving revision 1.11
diff -u -r1.11 SqlExpression.java
--- java/org/apache/torque/util/SqlExpression.java	26 Feb 2002 17:51:18 -0000	1.11
+++ java/org/apache/torque/util/SqlExpression.java	26 Feb 2002 18:48:41 -0000
@@ -62,6 +62,7 @@
 import org.apache.torque.om.DateKey;
 import org.apache.torque.om.ObjectKey;
 import org.apache.torque.om.StringKey;
+import org.apache.torque.TorqueException;
 import org.apache.commons.util.StringStack;
 
 /**
@@ -174,12 +175,13 @@
      * !=, LIKE, etc.
      * @return A simple SQL expression, e.g. UPPER(table_a.column_a)
      * LIKE UPPER('ab%c').
-     * @exception Exception, a generic exception.
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      */
     public static String build( String columnName,
                                 Object criteria,
                                 SqlEnum comparison )
-        throws Exception
+        throws TorqueException
     {
         // 'db' can be null because 'ignoreCase' is null
         return build( columnName, criteria, comparison, false, null );
@@ -199,14 +201,15 @@
      * functions.
      * @return A simple sql expression, e.g. UPPER(table_a.column_a)
      * LIKE UPPER('ab%c').
-     * @exception Exception, a generic exception.
+     * @throws TorqueException Any exceptions caught during processing will be
+     *         rethrown wrapped into a TorqueException.
      */
     public static String build( String columnName,
                                 Object criteria,
                                 SqlEnum comparison,
                                 boolean ignoreCase,
                                 DB db )
-        throws Exception
+        throws TorqueException
     {
         int addlength = (ignoreCase ? 40 : 20);
         StringBuffer sb = new StringBuffer(columnName.length() + addlength );
Index: templates/om/MapBuilder.vm
===================================================================
RCS file: /home/cvs/jakarta-turbine-torque/src/templates/om/MapBuilder.vm,v
retrieving revision 1.7
diff -u -r1.7 MapBuilder.vm
--- templates/om/MapBuilder.vm	30 Dec 2001 16:30:15 -0000	1.7
+++ templates/om/MapBuilder.vm	26 Feb 2002 18:48:42 -0000
@@ -3,6 +3,7 @@
 import java.util.*;
 import java.math.*;
 import org.apache.torque.Torque;
+import org.apache.torque.TorqueException;
 import org.apache.torque.map.MapBuilder;
 import org.apache.torque.map.DatabaseMap;
 import org.apache.torque.map.TableMap;
@@ -77,7 +78,7 @@
     /** 
      * The doBuild() method builds the DatabaseMap 
      */
-    public void doBuild() throws Exception
+    public void doBuild() throws TorqueException
     {
         dbMap = Torque.getDatabaseMap("$table.Database.Name");
 
Index: templates/om/Object.vm
===================================================================
RCS file: /home/cvs/jakarta-turbine-torque/src/templates/om/Object.vm,v
retrieving revision 1.18
diff -u -r1.18 Object.vm
--- templates/om/Object.vm	27 Dec 2001 18:28:59 -0000	1.18
+++ templates/om/Object.vm	26 Feb 2002 18:48:44 -0000
@@ -15,6 +15,7 @@
 import java.util.*;
 import java.math.*;
 import org.apache.torque.Torque;
+import org.apache.torque.TorqueException;
 import org.apache.torque.om.*;
 import org.apache.torque.util.BasePeer;
 import org.apache.torque.util.Criteria;
@@ -102,11 +103,11 @@
         #set ( $throwsClause = "" )
         #if ($complexObjectModel)
           #if ($col.isForeignKey())
-            #set ( $throwsClause = "throws Exception" )
+            #set ( $throwsClause = "throws TorqueException" )
           #end    
           #if ( $col.Referrers.size() > 0 )
             #if ($throwsClause == "")
-              #set ( $throwsClause = "throws Exception" )
+              #set ( $throwsClause = "throws TorqueException" )
             #end
           #end
         #end
@@ -235,7 +236,7 @@
      *
      * @param $className v
      */
-    public void set${pVarName}($className v) throws Exception
+    public void set${pVarName}($className v) throws TorqueException
     {
    #foreach ($columnName in $fk.LocalColumns)
     #set ( $column = $table.getColumn($columnName) )
@@ -265,7 +266,7 @@
    #end
    #set ( $pCollName = "${table.JavaName}s$relCol" )
     
-    public $className get${pVarName}() throws Exception
+    public $className get${pVarName}() throws TorqueException
     {
         if ( $varName==null && ($conditional) )
         {
@@ -302,7 +303,7 @@
      * overridden in <code>$table.JavaName</code>.
 #end
      */
-    public void set${pVarName}Key(ObjectKey key) throws Exception
+    public void set${pVarName}Key(ObjectKey key) throws TorqueException
     {
     #if ($fk.LocalColumns.size() > 1)
         SimpleKey[] keys = (SimpleKey[])key.getValue();
@@ -371,7 +372,7 @@
      *
      * @param $className l
      */
-    public void add${relColMs}($className l) throws Exception
+    public void add${relColMs}($className l) throws TorqueException
     {
         get${relCol}().add(l);
         l.set${table.JavaName}${suffix}(($table.JavaName)this);
@@ -387,7 +388,7 @@
      * the collection. Otherwise returns the results of 
      * get${relCol}(new Criteria())
      */
-    public Vector get${relCol}() throws Exception
+    public Vector get${relCol}() throws TorqueException
     {
         if ($collName == null)
         {
@@ -405,7 +406,7 @@
      * an empty collection or the current collection, the criteria
      * is ignored on a new object. 
      */
-    public Vector get${relCol}(Criteria criteria) throws Exception
+    public Vector get${relCol}(Criteria criteria) throws TorqueException
     {
         if ($collName == null)
         {
@@ -518,7 +519,7 @@
      * actually need in ${table.JavaName}.
      */
     protected Vector get${relCol}Join${relCol2}(Criteria criteria) 
-        throws Exception
+        throws TorqueException
     {
         if ($collName == null)
         {
@@ -576,7 +577,7 @@
      * actually need in ${table.JavaName}.
      */
     protected Vector get${relCol}JoinAllExcept${table.JavaName}(Criteria criteria) 
-        throws Exception
+        throws TorqueException
     {
         if ($collName == null)
         {
@@ -765,7 +766,7 @@
      * Stores the object in the database.  If the object is new,
      * it inserts it; otherwise an update is performed.
      */
-    public void save() throws Exception
+    public void save() throws TorqueException
     {
  #if ($complexObjectModel)
             save(${table.JavaName}Peer.getMapBuilder()
@@ -795,7 +796,7 @@
      * in this file instead of in the super class, BaseObject.
 #end
      */
-    public void save(String dbName) throws Exception
+    public void save(String dbName) throws TorqueException
     {
         DBConnection dbCon = null;
  #if ($complexObjectModel)
@@ -804,7 +805,7 @@
             dbCon = BasePeer.beginTransaction(dbName);
             save(dbCon);
         }
-        catch(Exception e)
+        catch(TorqueException e)
         {
             BasePeer.rollBackTransaction(dbCon);
             throw e;
@@ -850,7 +851,7 @@
      * the save() method and the connection details will be handled
      * internally
      */
-    public void save(DBConnection dbCon) throws Exception
+    public void save(DBConnection dbCon) throws TorqueException
     {
   #if ($complexObjectModel)
       if (!alreadyInSave)
@@ -943,7 +944,7 @@
 #foreach ($col in $table.PrimaryKeys)
     #if ($complexObjectModel)
         #if ( $col.isForeignKey() || ($col.Referrers.size() > 0) )
-            #set ( $throwsClause = "throws Exception" )
+            #set ( $throwsClause = "throws TorqueException" )
         #end
     #end
 
@@ -985,7 +986,7 @@
     /** 
      * Set the PrimaryKey with an ObjectKey
      */
-    public void setPrimaryKey(ObjectKey key) throws Exception
+    public void setPrimaryKey(ObjectKey key) throws TorqueException
     {
         SimpleKey[] keys = (SimpleKey[])key.getValue();
     #set ($i = 0)
@@ -1029,7 +1030,7 @@
     /** 
      * Set the PrimaryKey using a String.
      */
-    public void setPrimaryKey(String key) throws Exception
+    public void setPrimaryKey(String key) throws TorqueException
     {
         int prevPos = 0;
 
@@ -1089,7 +1090,7 @@
      * of its class.
      */
     public void setQueryKey(String key) 
-        throws Exception
+        throws TorqueException
     {
         setPrimaryKey(key);
     }
@@ -1105,10 +1106,10 @@
 #end
      */
 #if ($table.ChildrenColumn || $table.isAbstract()) 
-    public $table.JavaName copyInto($table.JavaName copyObj) throws Exception
+    public $table.JavaName copyInto($table.JavaName copyObj) throws TorqueException
     {
 #else
-    public $table.JavaName copy() throws Exception
+    public $table.JavaName copy() throws TorqueException
     {
         $table.JavaName copyObj = new ${table.JavaName}();
 #end
Index: templates/om/Peer.vm
===================================================================
RCS file: /home/cvs/jakarta-turbine-torque/src/templates/om/Peer.vm,v
retrieving revision 1.14
diff -u -r1.14 Peer.vm
--- templates/om/Peer.vm	4 Feb 2002 18:01:54 -0000	1.14
+++ templates/om/Peer.vm	26 Feb 2002 18:48:47 -0000
@@ -29,22 +29,22 @@
   *
 #end
   */
-public abstract class $basePrefix${table.JavaName}Peer 
+public abstract class $basePrefix${table.JavaName}Peer
     extends $table.BasePeer
 {
 #if (!$table.isAlias())
 
     /** the default database name for this class */
     public static final String DATABASE_NAME = "$table.Database.Name";
- 
+
      /** the table name for this class */
     public static final String TABLE_NAME = "$table.Name";
- 
-    /** 
-     * @returns the map builder for this peer 
+
+    /**
+     * @returns the map builder for this peer
      */
     public static MapBuilder getMapBuilder()
-        throws Exception
+        throws TorqueException
     {
         return getMapBuilder(${table.JavaName}MapBuilder.CLASS_NAME);
     }
@@ -89,7 +89,7 @@
     public static final int numColumns =  $table.NumColumns;
 
     /** A class that can be returned by this peer. */
-    protected static final String CLASSNAME_DEFAULT = 
+    protected static final String CLASSNAME_DEFAULT =
         "${package}.$table.JavaName";
 
     /** A class that can be returned by this peer. */
@@ -100,7 +100,7 @@
     {
         Class c = null;
         try
-        { 
+        {
             c = Class.forName(className);
         }
         catch (Throwable t)
@@ -127,22 +127,32 @@
      * resultset MUST return columns in the right order.  You can use
      * getFieldNames() in BaseObject to get the correct sequence.
      */
-    public static Vector resultSet2Objects (java.sql.ResultSet results) throws Exception
+    public static Vector resultSet2Objects (java.sql.ResultSet results) throws TorqueException
     {
-        QueryDataSet qds = null;
-        Vector rows = null;
         try
         {
-            qds = new QueryDataSet( results );
-            rows = getSelectResults( qds );
+            QueryDataSet qds = null;
+            Vector rows = null;
+            try
+            {
+                qds = new QueryDataSet( results );
+                rows = getSelectResults( qds );
+            }
+            finally
+            {
+                if (qds != null) qds.close();
+            }
+
+            return populateObjects (rows);
         }
-        finally
+        catch (SQLException e)
         {
-            if (qds != null) qds.close();
+            throw new TorqueException(e);
+        }
+        catch (DataSetException e)
+        {
+            throw new TorqueException(e);
         }
-
-        return populateObjects (rows);

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>