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.
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.
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.
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).
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 {
// ...
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With