Error even after throws Exception for thread.sleep - java

I am trying to make my Thread sleep and am making the method throws InterruptedException, however it is still giving the error "Unhandled exception"
#Before
public void setUp() throws InterruptedException{
simulatorList.forEach(simulation -> {
....
Thread.sleep(1000*60*1);
//giving error here
...
});
}

Because you calling Thread.sleep inside foreach, Below will solve your issue:
public void setUp() throws InterruptedException {
List<String> simulatorList = new ArrayList<>();
for (String s : simulatorList) {
Thread.sleep(1000 * 60 * 1);
}
}

Cause exception can be thrown from lambda. The easiest way to handle it is to rethrow the RuntimeException. like
public void setUp(){
new LinkedList<String>().forEach(simulation -> {
try {
Thread.sleep(1000*60*1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
If you really expect for InterruptedException, you can create your own exception extending RuntimeException, like RuntimeInterruptedException, rethrow it and then handle in your flow.

Related

Catching uncaught exceptions from CompletableFuture

I'm trying to catch uncaught exceptions on futures like this CompletableFuture.runAsync(() -> {throw new RuntimeException();});
My goal is to make these exceptions not silent when developpers forget to handle them.
Calling get() or join() and try/catch exceptions is not an option because it is not global to all usages of future in the code base
Adding .exceptionnaly(...) or handle(...) is not an option for the same reason. It's exactly what I'm trying to prevent
Here's what I do (which doesn't work)
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.setProperty("java.util.concurrent.ForkJoinPool.common.exceptionHandler", UncaughtExceptionHandler.class.getName());
CompletableFuture.runAsync(() -> {
System.out.println("async");
throw new RuntimeException();
});
System.out.println("Done");
Thread.sleep(1000);
}
static class UncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
#Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("Uncaught!");
}
}
}
It prints
Done
Async
What am I missing ?
EDIT
I tried this but still not working
public class Main {
public static void main(String[] args) throws InterruptedException {
CompletableFuture.runAsync(() -> {
System.out.println("Async");
throw new RuntimeException();
},
new ForkJoinPool(
Runtime.getRuntime().availableProcessors(),
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
(t, e) -> System.out.println("Uncaught!"), // UncaughtExceptionHandler
false));
System.out.println("Done");
Thread.sleep(1000);
}
}
It seems that the ForkJoinPool ignores its UncaughtExceptionHandler, and even its ForkJoinWorkerThreadFactory because I tried to define that as well
Version 1: everything works as it should, no exception thrown by the RunAsync method ... no exception handling occurs...
public static void main(String[] args) throws InterruptedException {
UncaughtExceptionHandler uncaughtExceptionHandler = new UncaughtExceptionHandler();
System.setProperty("java.util.concurrent.ForkJoinPool.common.exceptionHandler", UncaughtExceptionHandler.class.getName());
CompletableFuture.runAsync(() -> {
System.out.println("async");
}).exceptionally((ex) -> {
uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), ex);
return null;
});
System.out.println("Done");
Thread.sleep(1000);
}
static class UncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
public UncaughtExceptionHandler() { }
public void uncaughtException(Thread t, Throwable e) {
System.out.println("Uncaught!");
}
}
Output:
async
Done
Process finished with exit code 0
Version 2: Exception thrown by runAsync() and the exception handler does its thing.
public static void main(String[] args) throws InterruptedException {
UncaughtExceptionHandler uncaughtExceptionHandler = new UncaughtExceptionHandler();
System.setProperty("java.util.concurrent.ForkJoinPool.common.exceptionHandler", UncaughtExceptionHandler.class.getName());
CompletableFuture.runAsync(() -> {
throw new RuntimeException("Something went Wrong");
}).exceptionally((ex) -> {
uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), ex);
return null;
});
System.out.println("Done");
Thread.sleep(1000);
}
static class UncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
public UncaughtExceptionHandler() { }
public void uncaughtException(Thread t, Throwable e) {
System.out.println("Uncaught!");
}
}
Output:
Uncaught!
Done
Process finished with exit code 0
The two ways to handle exceptions:
.exceptionally(ex -> { your_code }) - gives you a chance to recover from errors generated from the original Future. You can log the exception here and return a default value.
.handle((result, ex) -> { your_code }) - called whether or not an exception occurs. Can also be used to handle exceptions
You are missing the fact that a CompletableFuture executes its task in the background (using an Executor) and handles any exception thrown by its task, in order to report the task’s status from methods like isCompletedExceptionally, so there is no uncaught exception.
The exception can be propagated by calling the CompletableFuture’s get() method:
CompletableFuture<?> future =
CompletableFuture.runAsync(() -> {
System.out.println("async");
throw new RuntimeException();
});
future.get();
System.out.println("Done");
Update:
Since you don’t want to wait for the exception, you can use exceptionally or exceptionallyAsync to respond to any exception thrown by the task:
CompletableFuture<?> future =
CompletableFuture.runAsync(() -> {
System.out.println("async");
throw new RuntimeException();
});
future.exceptionally(e -> {
System.out.println("Uncaught!");
return null;
});
System.out.println("Done");

How to handle exceptions when subscribing with Actions in RXJava

Here is a simple example:
Completable c = Completable.create(new CompletableOnSubscribe() {
#Override
public void subscribe(#NonNull CompletableEmitter e) throws Exception {
throw new Exception("Oh No!");
}
});
try {
c.subscribe(new Action() {
#Override
public void run() throws Exception {
Timber.v("It's ok");
}
});
}
catch (Exception e) {
e.printStackTrace();
Timber.v("Error");
}
In this case, I would have expected the exception to be caught however it causes the app to crash. So how are we supposed to handle the exception thrown by the inner class method?
I know that we could handle this differently by subscribing with a CompletableObserver but that adds extra verbosity that I'd like to avoid and I feel that there must be a way to handle this kind of Exception other the Action consumer wouldn't be very useful.
First of all RxJava already has a mechanism to catch Exceptions, But you need to implement onError Action.
have a look at following code:
Completable c = Completable.create(new CompletableOnSubscribe() {
#Override
public void subscribe(#NonNull CompletableEmitter e) throws Exception {
throw new Exception("Oh No!");
}
})
c.subscribe(new Action() {
#Override
public void run() throws Exception {
Timber.v("It's ok");
}
}, new Consumer<Throwable>() { // Second argument is onError Action
#Override
public void accept(Throwable e) {
// Handle you exception here.
Timber.v("Error");
}
});
Let's come to why your code is unable to catch exception even when you have put everything in try-catch, because exception being thrown is instance of RuntimeException class and your are catching instance of Exception class.
Try using RuntimeException, thrown exception should be caught then.
But it is not ideal way to catch exception instead use onError action described in above code snippet. And if your code is throwing Runtime exception then convert it into Exception using try-catch inside Observables.
Hope it helps.
There is an overload for handling errors:
c.subscribe(new Action() {
#Override
public void run() throws Exception {
Timber.v("It's ok");
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable e) {
e.printStackTrace();
Timber.v("Error");
}
});

JUnit handling of RuntimeException (specifically)

I tend to throw as many checked Exceptions up as possible: it declutters the code (and I regard checked Exceptions as a dubious aspect of Java). I tend to use them when "refining" code.. i.e. when it makes sense for the particular context.
This approach gets slightly complicated when overriding superclass/interface methods which don't throw the requisite Exception, and therefore I tend to do this:
#Override
public void close() {
try {
_close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
where _close is a private method which does all the business.
The problem when it comes to JUnit, if you actually want to test something where an exception is thrown by _close() is that the resulting RuntimeException seems to be handled by JUnit in an "unconditional" way: it seems always to stop the test with a failure message... even if you actually catch and deal with it in a try .. catch!
There is a sort of "workaround" for this which I've found (the CUT class closes all its closeableComponents when it is closed):
#Test (expected = RuntimeException.class)
public void errorFlagShouldBeSetIfAnyCloseablesThrowExceptionWhenCUTCloses() throws Exception {
Closeable spyCloseable = spy( new Closeable(){
#Override
public void close() throws IOException {
throw new IOException( "dummy" );
}});
spyCUT.addCloseableComponent( spyCloseable );
Exception blob = null;
try{
spyCUT.close();
}catch( Exception e ){
blob = e;
}
assertThat( spyCUT.getErrorFlag() ).isTrue();
if( blob != null ){
throw blob;
}
I.e. if you don't have this expected setting you always get a test failure (because of the RuntimeException "ignoring" the try .. catch). But in order to satisfy the expected you then have to rethrow the RuntimeException at the end of the test...
... is there any way of varying JUnit's handling of RuntimeExceptions?
Something must be wrong in your setup. JUnit does not have any such special handling for runtime exceptions.
I put together this MCVE; and it passes.
static class CUT {
void close(Closeable _close) {
try {
_close.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
#Test
public void test() throws Exception {
Closeable spyCloseable = Mockito.spy(new Closeable() {
#Override
public void close() throws IOException {
throw new IOException("dummy");
}
});
Exception blob = null;
try {
new CUT().close(spyCloseable);
fail("should have thrown");
} catch (Exception e) {
blob = e;
}
assertThat(blob.getMessage(), is("java.io.IOException: dummy"));
}
It is not exactly what you have up there; but "close enough" in my mind.
Long story short: your answer is coming from some other place. I suggest: do the same as I did: create a true mcve; and work your way from there!

Issue with Exception type handling when not throwing them - wanting a more generic version of multi-catch

Sorry for the TL;DR, but I feel like it needs some explanation or it will be misunderstood.
I have a method that makes a call to (generally external) code which I expect to sometimes throw a RuntimeException, and uses futures which can throw InterruptedException or ExecutionException, and I want to be able to return an ordered set of returned values to from the call up until the exception was thrown, and the exception that was thrown. I wrote something that works, but unfortunately, the way the code looks makes me feel like I'm doing something wrong. What I think I really want is multi-catch to be a more generic concept that. That would allow pretty clean code to solve it, kind of like this:
public class SomeResults {
private final Set<SomeReturnType> valuesReturned;
private final #Nullable RuntimeException | ExecutionException | InterruptedException exception;
public SomeResults(Set<SomeReturnType> valuesReturned, RuntimeException | ExecutionException exception {
this.valuesReturned = valuesReturned;
this.exception = exception;
}
public Set<SomeReturnType> getValuesReturned() {
return valuesReturned;
}
public #Nullable RuntimeException | ExecutionException | InterruptedException getException();
}
And have a method that wraps up making the calls to the external code
...
generateResults(Bar bar) {
// Setup code
Set<SomeReturnType> valuesReturned = new LinkedHashSet<>();
...
// loop
{
// stuff
... // exceptions in this method should throw except for this one external code call
try {
valuesReturned.add(externalCodeCallGetSomeReturnValue(bar))
}
catch( RuntimeException | ExecutionException | InterruptedException e) {
return new MyResults(valuesReturned, e)
}
...
}
return new MyResults(valuesReturned, (RuntimeException | ExecutionException | InterruptedException) null);
}
And subsequently do
SomeResults myResults = foo.generateResults(new Bar());
if(myResults.getException() != null) {
throw(myResults.getException);
}
Etc. Note that I do note always want to immediately rethrow the exception - it depends on who is using these results what they will want to do with them. I might do something like
try {
SomeResults myResults = foo.generateResults(new Bar());
Foobar Foobar = new Foobar(myResults);
}
catch(Exception e) {
// I don't want to see any exceptions from externalCodeCallGetSomeReturnValue(bar) here
...
}
Of course, I could let the exception get thrown in the function that generates results, instead of catching the exception and returning it as a result. This has two pretty big issues:
1. Now returning the set of values is going to be awkward - I could perhaps pass in a Set to the method that needs to "return" results and it modifies that set instead of returning a set. That allows the set to be up to date when the exception is returned. Eg
generateResults(Bar bar, Set<SomeReturnType> orderedListForMeToWrite) throws ExecutionException, InterruptedException
What if code surrounding the external method call throws a runtime exception? Now I have no easy way of distinguishing if the exception call was from the actual call to the external code, or something else! I actually ran into this issue when attempting this design. The code threw IllegalArgumentException from somewhere else, and my code handling treated it as if it had been thrown from SomeReturnType externalCodeCallGetSomeReturnValue(Bar bar). This seemed like a code health issue, which is why I moved away from this solution.
The solution I went with is to just store the exception as an Exception. However, I hated losing that type information. With no additional code work, if something wanted to throw it, it will have to declare "throws Exception", which is not good, similar code health issues there. Is there a good way to handle this situation?
What I ended up doing to get it to work the way I wanted it to is as follows:
public static class SomeResults {
private final Set<SomeReturnType> orderedReturnValues;
private final #Nullable Exception exception;
AsyncEchoesResult(Set<SomeReturnType> responses) {
this.orderedResponses = responses;
this.exception = null;
}
AsyncEchoesResult(Set<SomeReturnType> responses, RuntimeException exception) {
this.orderedResponses = responses;
this.exception = exception;
}
AsyncEchoesResult(Set<SomeReturnType> responses, ExecutionException exception) {
this.orderedResponses = responses;
this.exception = exception;
}
AsyncEchoesResult(Set<SomeReturnType> responses, InterruptedException exception) {
this.orderedResponses = responses;
this.exception = exception;
}
public Set<SomeReturnType> getResponses() {
return orderedResponses;
}
public #Nullable Exception getException() {
return exception;
}
public void throwExceptionIfExists() throws ExecutionException, InterruptedException {
try {
throw (exception);
}
catch (RuntimeException | ExecutionException | InterruptedException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException("Unexpected exception type in SomeResults",e);
}
}
}
Obviously, this is pretty ugly. If I hate the constructors as they are I can easily enough replace them with a single one that takes an Exception, but that weakening the type-checking to only the runtime call of throwException(). Anyway, are there alternatives that work better? Note that I'm using with JDK 7 so while JDK 8 answers would be interesting, that won't fix it for what I'm working on.
Since Java doesn’t allow declare a variable as “one of these types” you have to encapsulate the exception using the only construct which supports such a type set: a piece of code throwing that exception.
Consider the following type definitions:
interface ReThrower {
void reThrow() throws RuntimeException, ExecutionException, InterruptedException;
}
static class MyResult
{
private final Set<SomeReturnType> valuesReturned;
private final #Nullable ReThrower exception;
public MyResult(Set<SomeReturnType> valuesReturned, ReThrower exception) {
this.valuesReturned = valuesReturned;
this.exception = exception;
}
public Set<SomeReturnType> getValuesReturned() {
return valuesReturned;
}
public void reThrowException()
throws RuntimeException, ExecutionException, InterruptedException
{
if(exception!=null) exception.reThrow();
}
}
Then you can create a MyResult like this:
MyResult generateResults(Bar bar) {
// Setup code
Set<SomeReturnType> valuesReturned = new LinkedHashSet<>();
// …
// loop
{
// stuff
// … exceptions in this method should throw except for this one external code call
try {
valuesReturned.add(externalCodeCallGetSomeReturnValue(bar));
}
catch( RuntimeException | ExecutionException | InterruptedException e) {
// In Java 8 you would say: new MyResult(valuesReturned, ()->{ throw e });
return new MyResult(valuesReturned, new ReThrower() {
public void reThrow()
throws RuntimeException, ExecutionException, InterruptedException {
throw e;
}
});
}
//...
}
return new MyResult(valuesReturned, null);
}
Note that the inner class (or lambda expression in Java 8) implicitly stores the exception and that that implicit variable has the desired “one of the listed exception type”. Then, you can safely re-throw the exception:
MyResult results = new MultiCatchAndStore().generateResults(new Bar());
try
{
results.reThrowException();
} catch(RuntimeException | ExecutionException | InterruptedException ex)
{
// handle, of course, you could also have separate catch clauses here
}

Why I got an error saying that no one exception is thrown?

I have this in a class that implements Callable :
public class MasterCrawler implements Callable {
public Object call() throws SQLException {
resumeCrawling();
return true;
}
//more code with methods that throws an SQLException
}
In other class that execute this Callable, something like this:
MasterCrawler crawler = new MasterCrawler();
try{
executorService.submit(crawler); //crawler is the class that implements Callable
}(catch SQLException){
//do something here
}
But I got an error and a message of the IDE that an SQLException is never throw. This is because I'm executing in a ExecutorService?
UPDATE: So the submit don't throws an SQLException. How I can do to execute the Callable (run as thread) and catch the exception?
SOLVED:
public class MasterCrawler implements Callable {
#Override
public Object call() throws Exception {
try {
resumeCrawling();
return true;
} catch (SQLException sqle) {
return sqle;
}
}
}
Future resC = es.submit(masterCrawler);
if (resC.get(5, TimeUnit.SECONDS) instanceof SQLException) {
//do something here
}
When you call submit, you are passing an object. You are not calling call().
EDIT
Submit returns a Future f. When you call f.get(), the method can throw an ExecutionException if a problem is encountered during the execution of the callable. If so, it will contain the exception thrown by call().
By submitting your Callable to the executor, you are actually asking it to execute it (asynchronously). No need for further action. Just retrieve the future and wait.
ABOUT THE SOLUTION
Although your solution will work, this not very clean code, because you are hijacking the return value of Call. Try something like this:
public class MasterCrawler implements Callable<Void> {
#Override
public Void call() throws SQLException {
resumeCrawling();
return null;
}
public void resumeCrawling() throws SQLException {
// ... if there is a problem
throw new SQLException();
}
}
public void doIt() {
ExecutorService es = Executors.newCachedThreadPool();
Future<Void> resC = es.submit(new MasterCrawler());
try {
resC.get(5, TimeUnit.SECONDS);
// Success
} catch ( ExecutionException ex ) {
SQLException se = (SQLException) ex.getCause();
// Do something with the exception
} catch ( TimeoutException ex ) {
// Execution timed-out
} catch ( InterruptedException ex ) {
// Execution was interrupted
}
}
The submit method does not throw a SQLException.
It's because SQLException never will be throw by the crawler.
Try use finally instead of catch and see if you will have a problem or it works.
What IDE are you using? When I try your code, Eclipse complains "unhandled exception type Exception". This makes sense because the Callable interface defines the call() method to throw Exception. Just because your implementation class declares a more restricted exception type, the calling program cannot count on that. It expects you to catch Exception.

Categories

Resources