Why is catch block executed twice for a single exception?
I have the following code.
try{
Twitter twitter = new Twitter(user,password);
twitter.setStatus(txtStatus.getText());
JOptionPane.showMessageDialog(null, "Success");
txtStatus.setText("");
txtStatus.requestFocus();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Some Error.\n" +
" If you see this after Success Message..Ignore");
}
Here even after I get "Success message"开发者_运维知识库 Dialog, the "Some Error" dialog is also appearing. what may be the reason? Shouldnt the flow control escape the catch block if there were no run time errors.
Even if i get an exception also, the "Some Error" dialog is appearing twice.Why is this happenning?
You've left open the obvious possibility that one of the lines of code after the success dialog is displayed is throwing an exception. You're not catching a specific exception and you're not displaying a backtrace, so there's no way of telling. Start your debugging by using the caught exception's printStackTrace
method to find out where it's coming from.
Look at the Exception that you're catching and its stack trace, and you may be enlightened.
My guess: txtStatus
is null after your first dialog, or it's the requestFocus()
method that throws an Exception.
Your code may actually be called twice. Try putting a System.out.println statement at the top of the code or running it under a debugger and check it is actually only being called once.
Try printing the stack e.printStackTrace()
- there might be an exception after the success message (e.g. a NullPointerException
with txtStatus
?)
Exception can be thrown in one of this two lines:
txtStatus.setText("");
txtStatus.requestFocus();
I agree with atomice here: your code is being called multiple times. Add the finally block + more sensible error feedback.
try{
Twitter twitter = new Twitter(user,password);
twitter.setStatus(txtStatus.getText());
JOptionPane.showMessageDialog(null, "Success");
txtStatus.setText("");
txtStatus.requestFocus();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Some Error.\n" + e.getMessage());
}
finally {
JOptionPane.showMessageDialog(null, "Finally");
}
And I'll throw my two cents in as well.
Stick a break point on the first line and watch it with a debugger. You'll quickly see if it is being run twice, if something is null, and where the error is.
The debugger is your friend :-)
精彩评论