Quick Search for:  in language:    
Performance,seem,like,doing,good,putting,tryc
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
Java/ Javascript Stats

 Code: 220,465. lines
 Jobs: 89. postings

 How to support the site

 
Sponsored by:

 
You are in:
 

Does your code think in ink?
Login





Latest Code Ticker for Java/ Javascript.
Gobang
By Geniusbob Xu Qiang on 11/27


Click here to see a screenshot of this code!Salary
By Vikram Ivatury on 11/25

(Screen Shot)

Click here to see a screenshot of this code!A (part10) Powerful Swing Code to Maintain CD Database
By James Smith K on 11/25

(Screen Shot)

String Calculator
By MadokaCoder on 11/24


Chobi Dekha
By ShuvoRim on 11/23


Click here to see a screenshot of this code!A basic Client Server application II
By Ronald Holland on 11/23

(Screen Shot)

Bookmark image
By darren kurn on 11/22


myFT
By Owolabi Oyapero on 11/22


Click here to see a screenshot of this code!Simple Socket example
By Steven McElrea on 11/20

(Screen Shot)

Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!

Affiliate Sites



 
 
   

Try/Catch Blues

Print
Email
 

Submitted on: 6/7/2002 12:46:54 AM
By: Sachin Mehra (Delhi, India) 
Level: Advanced
User Rating: By 13 Users
Compatibility:Java (JDK 1.1), Java (JDK 1.2)

Users have accessed this article 8288 times.
 
(About the author)
 
     Performance - It may seem like you are doing good putting try/catch blocks all throughout your code, but you are probably being redundant.

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
Try/Catch Blues <--[if gte mso 9]> Sachin default 1 21 2002-06-07T04:20:00Z 2002-06-07T04:41:00Z 1 914 5215 43 12 6117 10.2625 <--[if gte mso 9]> Clean Clean MicrosoftInternetExplorer4 <--[if gte mso 10]>

Try/Catch Blues

Error Checking Gone Horribly Wrong.

Technical Article by Sachin Mehra (sachinweb@hotmail.com)

 

It may seem like you are doing good putting try/catch blocks all throughout your code, but you are probably being redundant.  When you declare a try/catch block in Java you cause the compiler to create “protected zones” of execution which require the runtime to do boundary checks and create further processing for the system.  You are not making the program more stable by doing this, you are making it many times slower!

 

If you have a try/catch block which has only one line of code inside the try { …you are
probably being inefficient. 

 

Here is an example of a bad piece of code:

 

Example 1a:

 

public HashTable doEvent(Event event) throws CBException {

  Connection conn = null;

  EntityClass entClass = null;

  ArrayList list = null;

  try {

try {

              conn = dataAdapter.getConnection(DataSource.PRIMARY);

}

catch (Exception e) {

              System.out.println(“[SomeClass] An error occurred obtaining connection: “ + e.getMessage());

}

try {

              entClass = new EntityClass();

              list = entClass.list(conn);

}

catch (Exception e) {     

              System.out.println(“[SomeClass] An error occurred obtaining data from the Entity: “ + e.getMessage());

}

try {

       result.put(“stuff”, list);

}

catch (Exception e) {

       System.out.println(“[SomeClass] An error occurred putting data into HashTable: ” + e.getMessage());

}

  }

  catch (Exception e {

       System.out.println(“[SomeClass] An error occurred in the method: “ + e.getMessage());

  }

  finally {

       dataAdapter.releaseConnection(conn);

  }

}     

 

 

The above example is a terrible piece of code.  It is inherently inefficient, represents poor error handling (despite the try/catch blocks) and is very ugly to look at to say the least.  For one, doing a boundary check on dataAdapter.getConnection(DataSource.PRIMARY) is pointless, why would you create a unique boundary for this.  This represents poor thinking.  Consider the following example of much more “cleaned up code”.

 

Example 1b:

 

public HashTable doEvent(Event event) {

  Connection conn = null;

  EntityClass entClass = null;

  ArrayList list = null;

  try {

       conn = dataAdapter.getConnection(DataSource.PRIMARY);

       entClass = new EntityClass();

       list = entClass.list(conn);

result.put(“stuff”, list);

  }

  catch (Exception e {

       System.out.println(“[SomeClass] An error occurred in the method: “ + e.getMessage());

  }

  finally {

       dataAdapter.releaseConnection(conn);

  }

  return result;

}     

 

 

The above method in Example 1b is just as effective as Example 1a at handling exceptions, and its execution time is much faster.  Think logically, if for example the dataAdapter.getConnection() method fails, the Exception will still be caught by the one single catch block.  Also, you can generally rely on the message coming from the ConnectionPoolManager, and DataAdapter to pass an understandable failure message. 

 

Lets take a look at another bad habit:

 

Example 2a:

 

try {

   try {

      compEntity.fetch(conn, compToolEvent.getComponentId());

      ArrayList roles = genRolesEntity.list(conn);

 

      results.put("roles", roles);

      results.put("component", compEntity);

   }

   catch (CBException e) {

      throw new CBException(“Error: “ + e.toString());

   }

   catch (Exception e) {

      throw new CBException(“Error: “ + e.toString());

   }

   … Hidden Code Here …

}

catch (Exception e) {

      throw new CBException(“Error: “ + e.toString());

}          

 

 

First of all, if you don’t see a problem in the above block of code then you don’t understand Exceptions.    The above code shows massive redundancy in the error handling.   Let’s say for example that compEntity.fetch() throws a CBException, this is what happen at runtime:

 

1.  Line: compEntity.fetch(conn, compToolEvent.getComponentId()) Throws a CBException

2.  CBException is CAUGHT by first catch block.

3.  A NEW CBException is THROWN.

4.  CBException is caught in the Exception catch block at the bottom.

5.  A NEW CBException is THROWN.

 

So what’s the problem you ask?  There are three big problems, and they are that: Three CBExceptions are instantiated instead of one!  But what does it matter? A lot actually, this type of boundary checking is expensive and foolish.  Consider this revised code.

 

Example 2b:

 

try {

   try {

      compEntity.fetch(conn, compToolEvent.getComponentId());

      ArrayList roles = genRolesEntity.list(conn);

 

      results.put("roles", roles);

      results.put("component", compEntity);

      return results;

   }

   catch (CBException e) {

      throw e;

   }

   catch (Exception e) {

      throw e;

   }

   … Hidden Code Here …

}

catch (CBException e) {

      throw e;

}

catch (Exception e) {

      throw new CBException(“Error: “ + e.toString());

}          

 

 

The above example makes much more sense.  When we catch a CBException, we just throw the existing CBException instance which is caught again and thrown to the higher level.  In this case we only create one Exception object.   The above example is once again also inherently redundant anyways, and can be even further compressed into the following example (remembering the discussion earlier):

 

Example 2c:

 

try {

   compEntity.fetch(conn, compToolEvent.getComponentId());

   ArrayList roles = genRolesEntity.list(conn);

 

   results.put("roles", roles);

   results.put("component", compEntity);

   return results;

   … Hidden Code Here …

}

catch (CBException e) {

   throw e;

}

catch (Exception e) {

   throw new CBException(“Error: “ + e.toString());

}          

 

 

 

That’s more like it.  But it could still be better, but that can wait until a later article.

 

 

Final Words

 

To re-iterate, don’t use excessive try/catch blocks.  Plan more carefully, and also take advantage of stacked catches to encapsulate code rather than creating many protected areas.   Performance is a very important.

 


Other 1 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this article(in the Advanced category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
6/7/2002 1:34:25 AM:Manu Mehrotra
Cool Work Man.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/13/2002 6:09:39 PM:Charles Chadwick
Excellent work, keep it up.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | Java/ Javascript Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.