This will be done:
private static final ScheduledExecutorService sExecutor = Executors.newSingleThreadScheduledExecutor(); // Main public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { try { createAndShowGUI(); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } // Swing GUI private static void createAndShowGUI() throws ExecutionException, InterruptedException { // Just create a swing thing. Boring JFrame frame = new JFrame("Title String"); JLabel label = new JLabel("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(label); frame.getContentPane().setLayout(new FlowLayout()); frame.pack(); frame.setVisible(true); // ******************************************** // INTERESTING CODE HERE. We schedule a runnable which assert false // but we never see a console assert error! // ******************************************** ScheduledFuture<?> future = sExecutor.schedule(new Runnable() { @Override public void run() { doAssertFalse(); } }, 0, TimeUnit.SECONDS); future.get(); } public static void doAssertFalse() { System.out.println("About to assert False"); assert false; System.out.println("Done asserting False"); }
Note. I save the result of schedule in the variable ScheduledFuture . The exception is not returned until you call the get() method in the future. All exceptions are thrown in an ExecutionException .
Unfortunately, this blocks, so another way to get an exception is as follows:
// Swing GUI private static void createAndShowGUI() { // Just create a swing thing. Boring JFrame frame = new JFrame("Title String"); JLabel label = new JLabel("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(label); frame.getContentPane().setLayout(new FlowLayout()); frame.pack(); frame.setVisible(true); // ******************************************** // INTERESTING CODE HERE. We schedule a runnable which assert false // but we never see a console assert error! // ******************************************** sExecutor.schedule(new Runnable() { @Override public void run() { try { doAssertFalse(); } catch (Error e) { e.printStackTrace(); } } }, 0, TimeUnit.SECONDS); } public static void doAssertFalse() { System.out.println("About to assert False"); assert false; System.out.println("Done asserting False"); }
Please note that I am breaking an error, not an exception. I do this because Assertions throws java.lang.AssertionError, and not an * Exception.
I'm having trouble finding any kind of documentation in Javadoc saying that the ScheduledExecutorService swallows exceptions if you don't do this, but through my tests, which seem to be taking place.
source share