L
L
lague2018-03-25 20:13:33
Java
lague, 2018-03-25 20:13:33

How to properly catch exceptions in a multi-threaded javafx application?

There was a question. I have a GUI application. In the main stream resp. graphic interface. All time-consuming operations (such as a request to an http server or a database) are sent to a new thread (one is created for each operation). Threads can throw exceptions, but only the first thread knows how to respond to them (in some cases, the thread can be restarted, in some cases, the user can simply show an error so that he decides what to do with it). During these operations, the user is shown a progress bar or the status of the current operation. Accordingly, the main thread cannot be blocked.
Question: under such conditions, how to correctly catch all exceptions from threads and transfer them to the main thread for processing?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Alexandrov, 2018-03-25
@jamakasi666

The fact that the thread can crash is already a problem, catch exceptions inside the thread from your functions, the same request to the database \ http and already decide what to do by the exception, but not how not to drop the entire thread.

A
Alexander Yudakov, 2018-03-25
@AlexanderYudakov

Well, since the experts are silent, I will try to suggest:

// Хотите новый поток - пожалуйста, но я бы рекомендовал что-нибудь типа:
// public static ExecutorService ThreadPool = Executors.newFixedThreadPool(8)
new Thread() {
    @Override
    public void run() {
        Exception exception = null;
        try {
            // затратные по времени выполнения операции (такие как запрос к серверу http или БД)...
        } catch(Exception ex) {
            exception = ex;
        }
        Exception finalException = exception;
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                if (finalException != null) {
                    // Handle exception in UI thread
                } else {
                    // Handle result in UI thread
                }
            }
        });
    }
}.start();

Disclaimer: I haven't seen JavaFX.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question