Solved

How to throw Exception from a java method ?

Posted on 2011-03-17
9
1,427 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 

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

The Orion Papers

Are you interested in becoming an AWS Certified Solutions Architect?

Discover a new interactive way of training for the exam.

Question has a verified solution.

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

I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
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…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

734 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