Doubt try/catch/finally
Hi all
Say i have following program:
try {
line1. functioncall()
line2. .....
line3. .....
catch(..) {
print error
finally{
System.out.println("In finally");
}As per my understanding if there is some error in try block , then control will skip to catch and then to finally.
And other way, if there is no error then all lines in try block will be executed and control has to go to finally block.
And i see that there is no error (i have used try catch inside line1 function call also)
Now I am facing this problem.
In try block, line 1 is executed and getting into finally and there is also no error so it has skipped catch block. And in try block line2 and line 3 are skipped.
Can anybody tell me why is it so.
thanks
Ravi
What might be the problem?Sunspots. Not enough fiber. Government conspiracy.
These are just guesses, which is all we can do unless you read and obey the following:
Please post a short, concise, executable example of what you're trying to do. This does not have to be the actual code you are using. Write a small example that demonstrates your intent, and only that. Wrap the code in a class and give it a main method that runs it - if we can just copy and paste the code into a text file, compile it and run it without any changes, then we can be sure that we haven't made incorrect assumptions about how you are using it.
Post your code between [code] and [/code] tags. Cut and paste the code, rather than re-typing it (re-typing often introduces subtle errors that make your problem difficult to troubleshoot). Please preview your post when posting code.
Similar Messages
-
Basic (try catch finally)
Try catch and finally were thing i recently neglected to use unless my ide made me, but i was just reading on how to use them and I have a question about something i couldn't find an answer for:
objects you declare in try statements e.g.:
try{
BufferedReader br=...;
are only available in the scope of that try statement. Is this bad programming style or would "br" be automatically destroyed after the try statement is exited?Well, define "dispose". If there's some method on the object that you need to call to clean that object up, you'll have to declare the variable outside the try block and then call it:
Something it;
try {
it = SomethingFactory.createHeavyObject();
it.doSomething(); // may throw Horse exception
it.doSomethingElse();
} catch (Horse e) {
e.printStackTrace();
} finally {
it.releaseResources();
it = null; // only necessary if there will be a long time before "it" goes out of scope
// and even then maybe not if releaseResources() took care of the heavy stuff
}On the other hand, you should never have to do this:
Something it;
try {
it = new Something();
it.doSomething(); // may throw Horse exception
} catch (Horse e) {
e.printStackTrace();
} finally {
it = null;
}Instead you could just do:
try {
Something it = new Something();
it.doSomething(); // may throw Horse exception
} catch (Horse e) {
e.printStackTrace(); -
Comment on my use of try / catch / finally
Below is a code fragment from an application I'm working on. I have a couple questions about it. Is the way that I'm using "finally" correct? It's supposed to make sure the Connection gets closed. Note that I have a separate class close the Connection.
(ConnectionFactory is a class I wrote so I don't have to write the DB connection code over and over.)
Connection con = null;
try
con = ConnectionFactory.getPooledConnection(Constants.JNDI_DS_NAME_LOCAL);
Statement stmt = con.createStatement();
stmt.executeUpdate("DELETE FROM person WHERE ID='" + personFormBean.getID() + "'");
} catch (SQLException e)
System.out.println(e.getMessage());
e.printStackTrace();
} finally
ConnectionFactory.close(con);
}Here's how I close the Connection:
public static void close(Connection con)
try
if (con != null && !con.isClosed())
con.close();
} catch (SQLException e)
System.out.println(e.getMessage());
e.printStackTrace();
}My other question is about the code in the catch block. Is there anything different that should be done in the catch block?Below is a code fragment from an application I'm
working on. I have a couple questions about it. Is
the way that I'm using "finally" correct? It's
supposed to make sure the Connection gets closed.
Note that I have a separate class close the
Connection.Excellent. I do this, too. (First person I had suggest it was jverd on this forum.)
>
(ConnectionFactory is a class I wrote so I don't have
to write the DB connection code over and over.)
Connection con = null;
try
con =
con =
con =
ConnectionFactory.getPooledConnection(Constants.JNDI_D
S_NAME_LOCAL);
Statement stmt = con.createStatement();
stmt.executeUpdate("DELETE FROM person
FROM person WHERE ID='" + personFormBean.getID() +
} catch (SQLException e)
System.out.println(e.getMessage());
e.printStackTrace();
} finally
ConnectionFactory.close(con);
}Here's how I close the Connection:
public static void close(Connection con)
try
if (con != null && !con.isClosed())
con.close();
} catch (SQLException e)
System.out.println(e.getMessage());
e.printStackTrace();
}My other question is about the code in the catch
block. Is there anything different that should be
done in the catch block?Looks fine. I'd recommend that you add methods to explicitly close Statement and ResultSet, too. Call the method to close statement in the finally block before you close the Connection.
I think logging the stack trace is the best thing to do. Printing the stack trace is okay, as long as someone can actually SEE the System.out stream. I think printing the message is a waste.
Do you want commit/rollback logic for the DELETE?
I'd pass the Connection into the method so it can participate in a unit of work. I don't have SQL methods get their own statement. Let the caller be responsible for obtaining and closing the Connection.
CRUD operations in DAO is a nice pattern. I commend it to you.
You do a lot right here, but I think it's possible to do better still.
% -
Doubt in a Finally block ?
ques 1 :: public class Main {
public String test() throws Exception
try
throw new Exception();
catch(Exception e)
throw new Exception();
finally
public static void main(String[] args) {
try{
new Main().test();
catch(Exception e)
e.printStackTrace();
}According to sun documentation ,a method whose return type is String,int,.. must have return statement otherwise compiler will show an error.But according to this program it will not show any compiler error.Can you please suggest or explain me how this program is compiling.
I have fair idea, that when you throw any exception and after that if u give return statement then it will say its not reachable.
ques 2::
public String test() throws Exception
try
throw new Exception();
catch(Exception e)
throw new Exception();
finally
return "abc";
}Again am using same method but here am just returning an value. I want to know what will happen to that new Exception() object which we are throwing at catch block.Since its returning value as "abc".
If you just comment that return statement then it will throw Exception.
Please clarify this also.My first recommendation is that you build an experiment and see how it behaves. That way you will know without a doubt what to expect based on your coding style. I'm not in any way saying that the behavior is in any way different from what the documentation illustrates, only that if you build a test you'll know for sure. Otherwise, you'll know what we told you and what the documentation says.
Puckstopper's rules #6 - It is preferred to have a single return from any given method. The exception to this rule is if you reach a point in the code that is non-exceptional but creates a condition where the rest of the method should not execute. (There is another rule that relates to this condition that says that in this case the functionality should really be divided because it is clearly overly complex.)
That leads us to a basic code pattern.
int retVal = 0 ; // Initialize to a neutral condition or the default condition
try{
// Do some stuff that might cause an exception to be thrown
retVal = RESOLUTION_STATE
// Be specific about exceptions
catch(Exception e){
// Do something to handle the exception in a graceful and tidy manner.
// Code that simply barfs the stack trace will incur the wrath of the Exception Gods
finally{
// Do anything relating to the code in the try and only in the try that must happen no matter what
return retVal ;This does not address the question of whether the exception(s) can or should be handled here. Only a cohesive way of dealing with the try/catch/finally construct and returning from a method.
PS. -
Mechanics of a Try-Catch-Finnally
Could someone explain to me the mechanics of a try catch finally?
as i understand it, you put the word try then a block then a catch and an exception
like this
try
{...code...
}catch (Exception e) {System.out.println ("error message"); continue}ok, say the try is wrong what happens next?
this is my code.....and its bad.
int bromstead=0;
do {
System.out.print((bromstead + 1) + ". " + whereput);
try {
n = scan.nextInt();
r = scan.nextInt() - 1;
c = scan.nextInt() - 1;
}catch (Exception e) {System.out.println(compr + enter); continue;}//end of try
boolean goahead = (n <= 25 && n >= 1 && r >= 1 && r <= 5 && c >= 1 && c <= 5);
if (!goahead) {
System.out.println(range + enter);
continue;
squ.placer(n, r, c);
bromstead++;
if (bromstead % 5 == 0)
squ.display();
} while (bromstead < 25);Just read this tutorial and you'll know all about exceptions and catching them. (And, that way, no one has to try to write a tutorial - that's already written!)
http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html -
About the finally block of the try catch.
I know that finally block contains the code that will be executed in any condition of the try catch.
However, I think it is unneccessary, since the stack after the try catch stack will be executed any way.
Any one can help?
for example
try{
System.in.read();
catch(Exception e){}
finally
{ System.out.println("does this matter?");}and
try{
System.in.read();
catch(Exception e){}
System.out.println("does this matter?");However, I think it is unneccessary, since the stackafter the try catch
stack will be executed any way.That does assume that you catch and handle the error
appropriately.
Of course this is valid as well, and demonstrates
when you would WANT a finally clause.
Connection con = null;
Statement stmt = null;
try{
con = Database.getConnection();
stmt = con.createStatement("Select * from dual");
// maybe something throws an exception here?
finally{
if (stmt != null){
stmt.close();
if (con != null){
con.close();
The finally block here might throw a null pointer exception itself use
null!=stmt null!=stmt -
Hi all,
I have one doubt regarding the try catch mechanism. In my class I have a try catch block. And in my catch block i am doing some db(insert) operations. Is it possible for me to add another try catch to this perticular catch block?
I have given a sample what i am looking for below.
eg: try{
}// end of try
catch{
try{
}// end of try in catch
catch{
}//end of catch in catch
}end of main catch
Please give some suggestions on this.
Thanks and regards,
Jithesh PMJitheshOnJava wrote:
Hi all,
I have one doubt regarding the try catch mechanism. In my class I have a try catch block. And in my catch block i am doing some db(insert) operations. Is it possible for me to add another try catch to this perticular catch block? Yes. Did you try it? -
Finally block should executed whether try goes successfully or the program goes to catch.
Am I right?
I have this kind of code here using BEA WLS:
* @jpf:action
* @jpf:forward name="success" path="reportView.jsp"
* @jpf:forward name="error" path="../error.jsp"
protected Forward viewReport(ViewReportForm vrForm)
try{
return new Forward("success");
catch(Exception e){
log.error(this,e);
e.printStackTrace();
getRequest().setAttribute("errorMessage",e.getMessage());
return new Forward("error");
finally
try
if (conn!=null)
conn.close();
if (rs!=null){
rs.close();
if (stmt!=null)
stmt.close();
conn=null;
rs=null;
stmt=null;
array=null;
params=null;
query=null;
q_where_pp=null;
html=null;
*System.out.println("Testing finally block");*
catch(Exception e)
log.error(e);
e.printStackTrace();
}Note that I put System.out.println("Testing finally block"); to test whether finally block gets executed.
When try goes fine which is return to page reportView.jsp the finally will be executed.
But when it goes wrong which goes to error.jsp the finally block never print out the sentence.
Which make me confuse, why finally block never executed after catch block.
Anyone could help me?pramudya81 wrote:
finally
try
if (conn!=null)
conn.close();
if (rs!=null){
rs.close();
if (stmt!=null)
stmt.close();
conn=null;
rs=null;
stmt=null;
array=null;
params=null;
query=null;
q_where_pp=null;
html=null;
*System.out.println("Testing finally block");*
catch(Exception e)
log.error(e);
e.printStackTrace();
First of all, your finally is after a bunch of statements, so if any of those statements throw an exception, your println() will never be executed. Finally does not mean that everything in the finally block gets executed even if they throw exceptions, it means execution will begin in the finally block before leaving the method try/catch.
Second, closing connections, result sets, and statements can all throw exceptions (you know this because you put a try/catch block around it). And they're pretty much guaranteed to throw an exception in this case: Closing a connection closes all the statements associated with it (and closing a statement will close the resultset associated with it). So when you try to close the resultset, it's already closed. This should've showed up in your logs. You need to re-order your closes, and put each close in its own try/catch block. -
Need HELP with finally() in nested try-catch
hi,
i am having trouble with deadlock and wondering if its due to an incorrect use of finally nested within multiple try catch blocks.
is the inner finally() required, will the outer one get executed, or will the two finally() statements get executed...??
the deadlock happens very infrequently to accurately test.
try {
try {
catch (InterruptedException e) {
return;
catch {
finally {
//will this be executed be executed by the inner throw statement
}or is an inner finally required
try {
try {
catch (InterruptedException e) {
return;
//this finally is NEW....is it needed!
finally {
//will this be executed. will both get executed
catch {
finally {
//will this be executed also, or completely ignored if exception throw from inner try/catch
}inner/outer, which one is executed first?
more info pls.I mean, really. How hard is it to find out for yourself?
public class TestFinally {
public static void main(String[] args) {
try {
try {
throw new RuntimeException("Whatever");
} finally {
System.out.println("Inner finally");
} finally {
System.out.println("Outer finally");
}I'll leave it to your imagination as to how to modify this class to confirm the answers to your original question. -
Doubt on try/catch exception object
why it is not advisable to catch type exception in try catch block. Its confusing me. If i catch exception object then it will show whatever exception occured.
btw, i was just go through duke stars how it works and saw this
http://developers.sun.com/forums/top_10.jsp
Congrats!Because there are many different kinds of Exception. If you have some specific local strategy for dealing with a particular excepion then you should be using a specific catch block.
If you don't then you should allow the expection to end the program, and ideally you should deal with all the expceptions in one top-level handler, so you should throw, rather than catch the exceptions in your methods. Often at the outer most level of the program or thread you will actually catch Throwable (not just Exception) to deal with any unanticipated problems in a general kind of way.
Also, you should be keeping track of what exceptions might be thrown, so that rather than using Exception in a throws clause or catch block, you should use the particular exceptions. Exceptions, generally, indicate a recoverable error that you really ought to be recovering from rather than just printing a stacktrace.
That's why exceptions are treated differently from runtime errors. -
I have a set of file IO operations, like file opening, buffering, writing etc. . Can I enclose everything in one try-catch or have use separate for each file IO operations
If any one of them will cause your method to "fail", then use a single try block.
You could have tried this for yourself. Ie written the codr this way and seen if it compiles without error. Even tested it with IOExceptions that are easy to cause (like nonexistant files or files you don't have permission to write to etc).
Sometimes there might be action you can do to recover from an exception. In that case one particular step might use its own try block. Note: you can nest try blocks, also. -
Some simple question , but i dont know...try & catch ..
Hi i was working on a media player and i've faced some problems...like what exactly does the try&catch do ??
and in the Player class what the realize() and prefetch do ??
Thank you in advance..
Mulham HaffarIf you are in doubt when or what exceptions to catch, use the java compiler as your guide. You will get compile time errors that clearly name the exception you have to catch with the line of code that could cause the exception/error. Then do the following:
try {
// the code that could throw the exception
} catch ([the-name-exception] e) {
e.printStackTrace();
// or do something else relevant here - this code gets executed when the exception is thrown
} finally {
// this is an optional block that is always executed before returning from the method (even if there was an exception thrown - do stuff like closing resources here
}where [the-name-exception] is the exception class I mentioned earlier.
You can also declare a method to throw the exception if you don't want to catch it. Just use the keyword "throws" followed by the class name of the exception. Then any place where you call the method will have to catch the exception.
You can also find out what exceptions are being thrown by looking in the JavaDocs. There is plenty more, but that is what you will need to get your program compiling. -
RAISERROR with Try/Catch does not exit after exception in catch block
I am trying to propogate an error from within my proc out to the caller.
In the attached example I have 2 sets of try catch blocks.
I raiserror in the first
catch the error and then raiserror again. (I expect to exit)
I do not expect :
to get to print 'post test'
to get to second try block.
but this does not exit, instead the code flows as per 2 runs.
I do not understand the reason for the flows, as it seems counterintuitive to be raising an error but then still print following exceptions. I cannot seem to find any references that explains this behaviour.
running tests together results
print '-------------------------------------------------------'
print 'test 15'
exec test_raiseerror 15
print '-------------------------------------------------------'
print 'test 16'
exec test_raiseerror 16
print '-------------------------------------------------------'
print 'test 17'
exec test_raiseerror 17
print '-------------------------------------------------------'
print 'test 18'
exec test_raiseerror 18
print '-------------------------------------------------------'
'RESULTS'
test 15
error number provided: 15
Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 21
name hello 15
post test
15
Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 37
name hello 2 15
post test2
test 16
error number provided: 16
Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 21
name hello 16
post test
16
Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 37
name hello 2 16
post test2
test 17
error number provided: 17
post test
17
post test2
test 18
error number provided: 18
post test
18
post test2
Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 21
name hello 17
Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 37
name hello 2 17
Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 21
name hello 18
Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 37
name hello 2 18
run tests seperately
exec test_raiseerror 15
error number provided: 15
RESULTS 15
Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 21
name hello 15
post test
15
Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 37
name hello 2 15
post test2
exec test_raiseerror 16
RESULTS 16
error number provided: 16
Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 21
name hello 16
post test
16
Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 37
name hello 2 16
post test2
exec test_raiseerror 17
RESULTS 17
error number provided: 17
post test
17
post test2
Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 21
name hello 17
Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 37
name hello 2 17
exec test_raiseerror 18
RESULTS 18
error number provided: 18
post test
18
post test2
Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 21
name hello 18
Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 37
name hello 2 18
CODEBLOCK:
if object_id('test_raiseerror','P') is not null
drop proc test_raiseerror
go
create proc test_raiseerror(@id as int) as
begin
begin try
declare @name varchar(20)
select @name = 'hello'
raiserror('name %s %d',@id,1,@name,@id)
print 'next'
end try
begin catch
declare @errormessage nvarchar(4000)
declare @errornum int
select @errormessage = error_message()
, @errornum = error_severity()
print 'error number provided: ' + convert(varchar(2),@errornum)
raiserror(@errormessage, @errornum,1)
print 'post test'
end catch
begin try
select @name = 'hello 2'
raiserror('name %s %d', @id,1,@name, @id)
end try
begin catch
select @errormessage = error_message()
, @errornum = error_severity()
print @errornum
raiserror(@errormessage, @errornum,1)
print 'post test2'
end catch
end
go
sqlserver 2008 & 2008 R2There is a Connect that describes a similiar complaint. But basically a raiserror inside a catch block does not terminate the procedure, it will continue with any additional code in the CATCH and FINALLY unless it hits a return statement.
http://connect.microsoft.com/SQLServer/feedback/details/275308/have-raiserror-work-with-xact-abort -
Escaping Boolean & Try/Catch blocks
Hi everyone-
You all have been so great. I finally got my double/int and all working on my calculator. Now, I have one more question that I cannot figure out. My booleans to escape when form is not completed correctly are not working. That is, it will output error, but then still attempt the rest, giving printouts/general exception. I tried using another boolean, but not working. Here is the applet:
www.quiltpox.com/HSTCalc.html
and code: www.quiltpox.com/HSTCalc.java
public void actionPerformed(ActionEvent evt) { //1
//declarations
try{
//reset all fields to null so user can start over
if(source == button1)
text1.setText("");
text2.setText("");
text3.setText("");
if(source == button2)
//check that all fields have been completed
if(t1.length() == 0 || t2.length() == 0 || t3.length() == 0)
output.append("\nPlease complete the required fields and try again.");
verify = false;
//parse string into integer data and verify
if(verify)
//parsing
if(size == 0 || numOfSquares == 0 || WOF == 0)
output.append("\nYou have entered a null value for Square Size, " +
"\nQuantity of HSTs, and/or Fabric Width. Please try again. ");
verify = false;
proceed = false;
if(proceed)
all codes/printouts/methods
} //end of if proceed
} //end of verify
} //end of if
} //end of try
catch (Exception e ) {
output.append("General Exception");
finally {
textArea1.setText(output.toString());
} //end of action performed(i hope i quoted that right)
Any ideas on how to resolve this? I know I could use a switch in a standard java, but not sure if that works with applet/try-catch.
Thanks again,
KimberlyYou need to use "else" clauses here.if(t1.length() == 0 || t2.length() == 0 || t3.length() == 0)
output.append("\nPlease complete the required fields and try again.");
} else {
if(size == 0 || numOfSquares == 0 || WOF == 0)
output.append("\nYou have entered a null value for Square Size, " +
"\nQuantity of HSTs, and/or Fabric Width. Please try again. ");
} else {
// all codes/printouts/methods -
Try catch implementation in dynamic query
I am fetching values by dynamic selection (select a,b,..from (var)...) .
Eveytime if I am selecting garbage value of var it will throw dump . Can u tell me how we implement try catch method / exception handling method so that I can avoid dump in dynamic query
Appropriate answer will rewarded with points that is for sure .Here is the usage of th try statements ...
PARAMETERS number TYPE i.
DATA: result TYPE p LENGTH 8 DECIMALS 2,
oref TYPE REF TO cx_root,
text TYPE string.
TRY.
IF ABS( number ) > 100.
RAISE EXCEPTION TYPE cx_demo_abs_too_large.
ENDIF.
PERFORM calculation USING number
CHANGING result
text.
CATCH cx_sy_arithmetic_error INTO oref.
text = oref->get_text( ).
CATCH cx_root INTO oref.
text = oref->get_text( ).
ENDTRY.
IF NOT text IS INITIAL.
WRITE / text.
ENDIF.
WRITE: / 'Final result:', result.
FORM calculation USING p_number LIKE number
CHANGING p_result LIKE result
p_text LIKE text
RAISING cx_sy_arithmetic_error.
DATA l_oref TYPE REF TO cx_root.
TRY.
p_result = 1 / p_number.
WRITE: / 'Result of division:', p_result.
p_result = SQRT( p_number ).
WRITE: / 'Result of square root:', p_result.
CATCH cx_sy_zerodivide INTO l_oref.
p_text = l_oref->get_text( ).
CLEANUP.
CLEAR p_result.
ENDTRY.
ENDFORM.
<b>please see this link for detailed explaination of the TRY & ENDTRY ...</b>
<a href="http://">http://help.sap.com/saphelp_nw04/helpdata/en/a9/b8eef8fe9411d4b2ee0050dadfb92b/content.htm</a>
reward points if it is usefull......
Girish
Maybe you are looking for
-
TS1398 Wifi slow after iOS 8 upgrade
Since upgrading to iOS 8 the wifi connection from both my iPad Air and iPhone 5 is so slow that watching video or streaming is not possible and many web pages take ages to load. I've rebooted and reset both devices and 2 different routers that are wo
-
Is it possible to stream video into a PDF document with HTML 5?
I'm trying to get around using flash to stream videos into my interactive PDF documents, as it's not supported on iOS. I'm wondering if there's a way to use HTML 5 to acomplish something similar. I have access to both InDesign CC and the latest versi
-
Viewing the Result Table Data?
Hello, Please let me know the steps how to see the result table data after running the Remuneration Statement or before running the Remuneration Statement.
-
We have some pdf files which that all pages seems blank when we open it in Adobe Reader X. We have also Adobe Acrobat 3D is installed on some clients and we can see all pages when we open these documents with Adobe Acrobat 3D. I can upload a sample f
-
hi all, i have a scenario where i need to read some dats from a HTML pag and send it to sap r/3 through IDOC. This needs to be done once in day. I have created a UDF whcih reads data from the webpage and puts it in to IDoc. but i am not sure about se