No exit from the exception

Why doesn't this code print an exception stack trace?

public class Playground { /** * @param args */ public static void main(String[] args) { startThread(); } private static void startThread() { ScheduledExecutorService timer = Executors .newSingleThreadScheduledExecutor(); Runnable r = new Runnable() { int dummyInt = 0; boolean dummyBoolean = false; @Override public void run() { dummyInt = Integer.parseInt("AAAA"); if (dummyBoolean) { dummyBoolean= false; } else { dummyBoolean= true; } } }; timer.scheduleAtFixedRate(r, 0, 100, TimeUnit.MILLISECONDS); } } 

How can i get this?

I would expect to see this:

 java.lang.NumberFormatException: For input string: "AAAA" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at Playground$1.run(Playground.java:25) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask$Sync.innerRunAndReset(Unknown Source) at java.util.concurrent.FutureTask.runAndReset(Unknown Source) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(Unknown Source) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(Unknown Source) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) 
+4
source share
3 answers

The worker probably installs its own exception handler in the stream, so the stack trace will not be output to the console. If an exception is thrown in Runnable , you can get it from the ScheduledFuture object returned by the scheduleAtFixedRate method:

 ScheduledFuture<?> future = timer.scheduleAtFixedRate(r, 0, 100, TimeUnit.MILLISECONDS); try { future.get(); } catch (ExecutionException e) { Throwable cause = e.getCause(); cause.printStackTrace(); } 
+8
source

The executing agency tends to swallow exceptions for some reason. This can make debugging a rather difficult task. Just add an attempt to catch the contents of your execution method as follows:

 public void run() { try dummyInt = Integer.parseInt("AAAA"); if (dummyBoolean) { dummyBoolean= false; } else { dummyBoolean= true; } } catch (Exception e){ e.printStackTrace(); } } 

Here is a related question.

+1
source

There is a similar question that provides the answer Unhandled exceptions with scheduled Java executives here in StackOverflow.

Basically what you can read in scheduleAtFixedRate () javadoc :

If any task execution encounters an exception, subsequent executions are suppressed

So, I would summarize here that you will never see your exceptions when submitting tasks via ScheduledExecutorService.scheduleAtFixedRate() .

0
source

Source: https://habr.com/ru/post/1304323/


All Articles