Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle different exceptions in Task?

I'm kinda new in JavaFX, and I didn't find any answer to this.

I'm trying to use Task to do some background calculation in a database. The problem is the following : How can I handle exceptions (SQLException, IOException etc ...) in my task.SetOnFailed(e -> ....) function ?

I tried this : e.getSource().getException().getMessage() but I don't think it is the right way to do this.

like image 676
Arthur Clerc-Gherardi Avatar asked Jun 09 '16 13:06

Arthur Clerc-Gherardi


People also ask

How do you handle different exceptions?

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.

How do you handle exceptions thrown by tasks?

You can also handle the original exceptions by using the AggregateException. Handle method. Even if only one exception is thrown, it is still wrapped in an AggregateException exception, as the following example shows. public static partial class Program { public static void HandleThree() { var task = Task.

How do you handle an exception in a project?

Generally speaking an exception is because something bad and unexpected happened, and so you should let it rise up, notify the user, do some logging, and then move on. In general, it should terminate the application (or request).


1 Answers

You can just check the type of the exception:

Task<Something> myTask = new Task<Something>() {
    @Override
    public Something call() throws Exception {
        // code...
        return something ;
    }
};

myTask.setOnFailed(e -> {
    Throwable exc = myTask.getException();

    if (exc instanceof SQLException) {
        // ... 
    } else if (exc instanceof IOException) {
       // ...
    } else {
       // ...
    }
});
like image 191
James_D Avatar answered Sep 29 '22 13:09

James_D