本文目录一览:
如何在java中创建一个“自定义异常类”?
public class sssss {\x0d\x0a\x0d\x0apublic static void main(String[] args) {\x0d\x0a\x0d\x0a System.out.print("Please input an Integer: ");\x0d\x0a \x0d\x0a int value = new Scanner(System.in).nextInt();\x0d\x0a \x0d\x0a try{\x0d\x0a if(value
回答于 2022-11-16
java自定义异常
代码修改了,如下,有疑问可以追问:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class NumExcp {
public static void main(String[] args) {
NumExcp ne = new NumExcp();
}
Frame frame;
Panel panel;
TextField tf;
Button btn;
NumExcp() {
frame = new Frame();
panel = new Panel();
btn = new Button("Check");
tf = new TextField("Enter an integer here between 10 to 100:");
Listener AL = new Listener();
btn.setEnabled(true);
frame.setVisible(true);
frame.setSize(400, 400);
frame.setLocation(200, 200);
panel.setSize(200, 200);
panel.setVisible(true);
frame.add(panel);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
panel.add(tf);
panel.add(btn);
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
btn.addActionListener(AL);
}
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
int n = Integer.valueOf(tf.getText());
check(n);
} catch (Num_Exception e1) {
e1.e_message();
}
}
}
public void check(int n) throws Num_Exception {
if (n 10 || n 100) {
throw new Num_Exception("请输入 between 10 to 100:");
} else {
tf.setText("Congrats!Your input is correct!");
}
}
class Num_Exception extends Exception {
private Num_Exception(String message) {
super(message);
}
public void e_message() {
JOptionPane.showMessageDialog(null, "Invalid input! " + this.getMessage(), "", JOptionPane.ERROR_MESSAGE);
}
}
}
java自定义异常类
public void MyException extends Exception{
public MyExceprion(){
System.out.println("自定义异常");
}
}
public class Exam{
public static void mul() throws MyException{
if(自己写条件){
throw new MyException();
}
}
}
这个应该能看懂吧,我只是写了个结构没写完整程序的,你看懂这个就行,定义一个自定义异常,然后在你需要的地方抛出异常,在主方法中调用方法的时候达到一定条件就会抛出异常