Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How to throw Exception from a java method ?

Posted on 2011-03-17
9
Medium Priority
?
1,607 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:
Gurvinder Pal Singh earned 400 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:Gurvinder Pal Singh
ID: 35163150
specific error message will be the parameter to that BusinessException
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

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 400 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 400 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

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…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

963 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