Java Exceptions – A couple of nice little tricks

Been reading today about Java Exceptions and have noted a couple of nice little tricks. These ‘tricks’ would also apply to C#, and presumably many other languages.

Trick One – No need to catch to re-throw exceptions

The first little trick would be taking this code:

   try {
        // do something to throw an exception
   } catch (Exception e) {
        throw e;
   } finally {
        // do tidy-up
   }

When in actual fact there is no need to handle the catch, as it’ll be thrown anyway – so the code could be shorten to:

   try {
       // do something to  throw an exception
   }  finally {
       // do tidy-up
   }

I reckon I’ve been quite guilty in the past of introducing extra lines just to re-throw the exception, and whilst not  the end of the world certainly some needless code being produced.

Trick Two  – Set member variables after finally (or successful try?)

Rather than set member variables and then use them, risking something not completing properly – use local variables and then update members upon success case. The article I was reading was recommending doing them at the end of the function – however I’ve always had a habit of doing them at the end of the try. I guess both ways work, unless someone wants to better educate me?!?

An example probably speaks a 1000 words, so incredibly straight-forward:

Instead of this:

   function initialiseSql(String sql) {
      try {
         this.sql = sql;
         executeSql();
      }  finally {
         // do tidy-up
      }
   }

Potentially do this (although I’m debating the passing of the member variables and code re-use, but lets not get too deep at this point):

   function initialiseSql(String sql)  {
      try {
         executeSql(sql);
         this.sql = sql;
      } finally {
         // do tidy-up
      }
   }

or

   function initialiseSql(String sql)  {
      try {
         executeSql(sql);
      } finally {
         // do tidy-up
      }
      this.sql = sql;
   }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s