简体   繁体   中英

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.

尝试打印堆栈e.printStackTrace() - 成功消息后可能有异常(例如带有txtStatusNullPointerException ?)

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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM