Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to throw Exception from a java method ?

Posted on 2011-03-17
9
Medium Priority
?
1,553 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:
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
Technology Partners: 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!

 

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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
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…
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 theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

704 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