Solved

How to throw Exception from a java method ?

Posted on 2011-03-17
9
1,331 Views
Last Modified: 2012-06-27
I have a DAO  code which saves data in database  like this ..
public int save(MyVO vo)throws Exception
{

try{
	//insert table1

	//insert table 2

	//insert table 3

	//insert table 4

	//insert table 5



} catch (Exception e) {
    	System.out.println("Here1");
    	con.rollback();       
		LOGGER.debug(e.getMessage());
		e.printStackTrace();
		throw new Exception(e.getMessage());
	} finally {
		try {
			if (rs != null)
				rs.close();

		} catch (Exception i) {
			System.out.println("Here2");
			con.rollback();       
			i.printStackTrace();
			LOGGER.debug(i.getMessage());
			throw new Exception(i.getMessage());
		}
		try {
			if (ps != null)
				ps.close();

		} catch (Exception i) {
			System.out.println("Here3");
			con.rollback();       
			i.printStackTrace();
			LOGGER.debug(i.getMessage());
			throw new Exception(i.getMessage());
		}
		try {
			if (stmt != null)
				stmt.close();

		} catch (Exception i) {
			System.out.println("Here5");
			con.rollback();       
			i.printStackTrace();
			LOGGER.debug(i.getMessage());
			throw new Exception(i.getMessage());
		}
		try {
			if (con != null)
				con.close();

		} catch (Exception i) {
			System.out.println("Here4");
			con.rollback();       
			i.printStackTrace();
			LOGGER.debug(i.getMessage());
			throw new Exception(i.getMessage());
		}
	}
	


}

Open in new window


when I run PMD  rules , I get this warning  

      A method/constructor shouldn't explicitly throw java.lang.Exception
Rule:  http://pmd.sourceforge.net/rules/typeresolution.html#SignatureDeclareThrowsException


How do I improve my code ?
0
Comment
Question by:cofactor
9 Comments
 
LVL 40

Accepted Solution

by:
gurvinder372 earned 100 total points
ID: 35163119
catch specifically, the SQLException, and throw new RuntimeException()

check this link
http://radio-weblogs.com/0122027/stories/2003/04/01/JavasCheckedExceptionsWereAMistake.html
0
 

Author Comment

by:cofactor
ID: 35163143
>>>catch specifically, the SQLException, and throw new RuntimeException()

RuntimeException()  ?   Well...Ok.I can throw a custom exception say BusinessException  in place of RuntimeException .  Is it possible to throw specific error message from this layer ? which way ?
0
 
LVL 40

Expert Comment

by:gurvinder372
ID: 35163150
specific error message will be the parameter to that BusinessException
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:cofactor
ID: 35163200
>>specific error message will be the parameter to that BusinessException

yes .  but as there are inserts for  5 tables , could I throw a specific error message for which table the error occured.

For example:  "Error ocuured to insert into table1"  ...kind of error message.
0
 
LVL 14

Assisted Solution

by:CPColin
CPColin earned 100 total points
ID: 35163253
gurvinder372 is right that you should specifically catch the SQLException instead of Exception; if you catch Exception, you might catch more than you intended. I recommend that you don't wrap the SQLException in a RuntimeException, though. When you throw the exception again at the end, just re-throw the one you just caught, instead of making a new one.

The warning that methods should not explicitly throw java.lang.Exception is because throwing that type isn't very specific or useful. Declaring that the method will throw SQLException makes it more obvious what's going on.
0
 

Author Comment

by:cofactor
ID: 35163277
>>>Declaring that the method will throw SQLException makes it more obvious what's going on.

The reason I put Exception in the DAO class  if there is a exception occured e.g NumberFormatExceptio ..this will not be caught by SQLException.

0
 

Author Comment

by:cofactor
ID: 35163336
How about this ..I'm wrapping this way..

} catch (Exception e) {
    	LOGGER.debug("Exception occured in save");
    	LOGGER.debug(e.getMessage());
	    	try {
				con.rollback();
			} catch (SQLException e1) {
				LOGGER.debug("Rollback Exception occured in save");
				LOGGER.debug(e1.getMessage());
			}       
		
		throw new BusinessException("save operation failed");
		
	} finally{
    	try {
			if(ps!=null)ps.close();
			if(rs!=null)rs.close();
			if(con!=null)con.close();
			
			
		} catch (SQLException e) {
			LOGGER.debug("SQLException occured in save"+e);
			throw new BusinessException("save operation failed");
			
			
		}
	}

Open in new window

0
 
LVL 5

Expert Comment

by:josephtsang
ID: 35164011
Since the method return int, you should at least return a dummy int at the end of the method (after the catch block).

I think it may be complaining that if there is no error caught in your try-block, there is no int return nor any error thrown.
0
 
LVL 10

Assisted Solution

by:gordon_vt02
gordon_vt02 earned 100 total points
ID: 35166267
You really shouldn't have a catch (Exception e) block unless its absolutely necessary.  Otherwise you might catch more than you expect and may end up hiding a problem with your app.  You should catch only the exceptions you expect to be thrown by the code you are executing and, similarly, if you are throwing exceptions you should declare explicitly the exceptions your method will throw instead of using a catch-all "throws Exception."

If you want a custom error message for each table, you should wrap each of your inserts in their own try/catch block, otherwise you'll have to rely on the message in the exception thrown by your JDBC driver, which may or may not give you any help identifying which insert failed.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to parse custom JSON to POJO java 4 73
github account with ecipse 1 48
Java Timer (static) 9 44
Oracle SQL syntax check  without executing 6 55
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question