imho.ws |
![]() |
![]() |
![]() |
# 2 |
Member
Регистрация: 18.04.2002
Адрес: Ф туманах Новосибирска...
Сообщения: 378
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
Исключения которые не обрабатываются в потоке из которого они были брошены ловятся следующим образом:
Можно также установить обработчик исключений по-умолчанию для всех создаваемых потоков: Thread.setUncaughtExceptionHandler. Код:
package test; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.lang.Thread.UncaughtExceptionHandler; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class Test { private static UncaughtExceptionHandler uncaughtExceptionHandler; private static JFrame frame; private static JLabel infoLabel; private static int i; public static void main(String[] args) { uncaughtExceptionHandler = new ExceptionHandler(); frame = new JFrame(); JPanel panel; panel = new JPanel(); infoLabel = new JLabel(); JButton threadLaunchButton; threadLaunchButton = new JButton(); panel.add(threadLaunchButton, BorderLayout.CENTER); panel.add(infoLabel, BorderLayout.NORTH); threadLaunchButton.setAction(new ThreadLaunchAction()); frame.setContentPane(panel); frame.setSize(600, 400); frame.addWindowListener(new MainFrameCloseHandler()); frame.setVisible(true); } private static final class ExceptionHandler implements UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { infoLabel.setText("Exception with message: '" + e.getMessage() + "' was caught (" + i + ")!"); i++; } } private static final class MainFrameCloseHandler extends WindowAdapter { @Override public void windowClosing(WindowEvent e) { System.exit(0); } } @SuppressWarnings("serial") private static final class ThreadLaunchAction extends AbstractAction { public ThreadLaunchAction() { super("Throw exception"); } public void actionPerformed(ActionEvent e) { Thread t; t = new Thread(new Runnable() { public void run() { throw new RuntimeException("I am exception from thread."); } }, "Test thread"); t.setUncaughtExceptionHandler(uncaughtExceptionHandler); t.start(); } } }
__________________
Трофейные шляпки от гвоздей: ○○○○○○○○
Последний раз редактировалось EjikVTumane; 24.11.2007 в 13:13. Причина: немного дополнительной информации... |
![]() |