Home arrow static arrow Java Programming [Archive] - throws vs throw new Exception !!!!!
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - throws vs throw new Exception !!!!!
This topic has 4 replies on 1 page.

Posts:118
Registered: 3/15/01
throws vs throw new Exception !!!!!  
Aug 4, 2004 2:13 AM



 
Hi,

i have to write an application and manage some excpetions.
I ha to choices to write my methods :

First :

public void init() throws SQLExcpetion {

// do a connection to a DB and other stuff
}

Second:

public void init() throws SQLException {

try {

} catch ( Exception e ) {
throw new SQLException("Hello");
}
}

What is the right way to write methods to manage excpetions ? the first way or the second.
Both methods has to be called inside a main() method.
Cheers.

Stefano


 

Posts:964
Registered: 7/23/03
Re: throws vs throw new Exception !!!!!  
Aug 4, 2004 2:24 AM (reply 1 of 4)



 
this is all depend on whether you want to handle the exception in the method or leave it to the codes which called this method....

for example, if you want to log the error message or close any resources that have been used before pass the exception back to the other code, then, the 2nd method can be use...
 

Posts:13
Registered: 8/3/04
Re: throws vs throw new Exception !!!!!  
Aug 4, 2004 2:26 AM (reply 2 of 4)



 
The first one is the best, the second one is just silly...

The only time you should create a new instance of Exception is when you have something interesting to add. In all other cases, you can throw the original.

 

Posts:964
Registered: 7/23/03
Re: throws vs throw new Exception !!!!!  
Aug 4, 2004 2:32 AM (reply 3 of 4)



 
you can eliminate the creation of new instance of exception by doing this :
public void init() throws SQLException { try {  } catch ( SQLException e ) {//handle the exception here ...throw e; //rethrow the exception to be handle by other codes}}
 

Posts:4,496
Registered: 19/06/02
Re: throws vs throw new Exception !!!!!  
Aug 4, 2004 2:41 AM (reply 4 of 4)



 
If your method encounters an abnormal condition that it can't handle, it should throw an exception. When I say abnormal condition, I mean something that would not happen in the normal execution of that method. Also, remember that if you throw an unchecked exception the client can simply ignore it. Therefore if you think the exception needs to be handled you need to throw a checked exception. You should NOT throw exceptions in order to provide control flow for the normal execution of a program. Throwing an exception is expensive and throwing exceptions all over the shop is very bad programming style.
 
This topic has 4 replies on 1 page.