Why is the catch block executed twice for one 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 the "Successful message" dialog, the "Some error" dialog appears. what could be the reason? If the flow control did not exit the catch block, if there were no runtime errors.

Even if I get the exception, the "Some error" dialog also appears. Why is this happening?

+2


source to share


7 replies


You left open the obvious possibility that one of the lines of code after the success dialog displays an exception. You won't catch any particular exception, and you don't show a line back, so you can't tell. Start your debugging with the excluded method printStackTrace

that was discovered to find out where it came from.



+8


source


Take a look at the Exception you are catching and its stack trace and you may be enlightened.



My guess: txtStatus

is null after the first dialog or the method requestFocus()

that throws the exception.

+2


source


Your code can be called twice. Try putting the System.out.println statement at the top of your code, or running it under a debugger and check that it is actually only called once.

+1


source


Try to print the stack e.printStackTrace()

- there might be an exception after the success message (e.g. NullPointerException

with txtStatus

?)

+1


source


An exception can be thrown on one of two lines:

txtStatus.setText("");
txtStatus.requestFocus();

      

0


source


I agree with atom here: your code gets called multiple times. Add finally block + more sensible 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");
}

      

0


source


And I'll drop my two cents too.

Insert a breakpoint on the first line and watch it with the debugger. You will quickly see if it runs twice, if something is empty and where the error is.

The debugger is your friend :-)

0


source







All Articles