Runnable That Logs Runtime Exceptions
You can use VerboseRunnable
: with scheduled executor, for example:
public class Main { public static void main(String[] args) { Executors.newScheduledThreadPool(2).scheduleAtFixedRate( new VerboseRunnable( new Runnable() { @Override public void run() { // some operation that may lead to a runtime // exception, which we want to log through SLF4J } } ), 1L, 1L, TimeUnit.SECONDS ); } }
Now, every runtime exception that is not caught inside your Runnable
will be reported to log (using Logger
).
Two-arguments constructor can be used when you need to instruct the class about what to do with the exception: either swallow it or escalate. Sometimes it's very important to swallow exceptions. Otherwise an entire thread may get stuck (like in the example above).
The only dependency you need is (you can also download jcabi-log-0.24.3.jar
and add it to the classpath):
<dependency> <groupId>com.jcabi</groupId> <artifactId>jcabi-log</artifactId> <version>0.24.3</version> </dependency>