Solved

How to throw Exception from a java method ?

Posted on 2011-03-17
9
1,252 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
 

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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

758 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now