异常处理

//NumberFormatTest.java
import java.awt.*;
import java.awt.event.*;
public class NumberFormatTest extends Frame implements ActionListener {
    private TextField tf;
    private Button btn;
    private List list;
    public static void main(String[] args) {
        NumberFormatTest test = new NumberFormatTest();
        test.setSize(300,200);
        test.setVisible(true);
    }
    public NumberFormatTest() {
        Panel panel = new Panel();
        tf = new TextField(5);
        btn = new Button("确定");
        btn.addActionListener(this);
        list = new List();
        panel.add(new Label("inter a number:"));
        panel.add(tf);
        add(panel,BorderLayout.NORTH);
        add(btn,BorderLayout.SOUTH);
        add(list,BorderLayout.CENTER);
    }
    public void actionPerformed(ActionEvent e) {
        int num;
        try {
            num = Integer.parseInt(tf.getText());
            list.removeAll();
            list.add(Integer.toString(num));
        } catch(NumberFormatException exc) {
            tf.setText("");
            }
    }
}
原文地址:https://www.cnblogs.com/gride-glory/p/7668241.html