我想在用户关闭窗口时抛出异常,但我不确定这是否可行。以下是我想要做的一些代码:
import java.awt.event.*;
import javax.swing.*;
public class ExceptionTest extends JFrame{
public static void main(String[] args) {
try {
new ExceptionTest();
} catch (Exception e) {
e.printStackTrace();
}
}
public ExceptionTest() throws Exception{
super("Exception Test");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
super.windowClosed(e);
//Throw Exception
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
答案 0 :(得分:2)
您可以使用RunTimeException
代替,如下所示:
public ExceptionTest() {
super("Exception Test");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e)throws RuntimeException {
throw new RuntimeException("WindowClosedException");
}
});
答案 1 :(得分:2)
基本上你可以在那里抛出任何类型的RuntimeExceptions。 您可以在此处找到RuntimeExceptions列表:RuntimeException (Java Platform SE 6)
import java.awt.event.*;
import javax.swing.*;
public class ExceptionTest extends JFrame{
public static void main(String[] args) {
try {
new ExceptionTest();
} catch (Exception e) {
e.printStackTrace();
}
}
public ExceptionTest() throws Exception{
super("Exception Test");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
super.windowClosed(e);
throw new IllegalArgumentException("User closed this window!");
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
答案 2 :(得分:1)
您可以抛出RuntimeException
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
super.windowClosed(e);
throw new RuntimeException();
}
});