Home >Java >javaTutorial >How to Catch ArrayIndexOutOfBoundsException in SwingWorker and Executor Threads?

How to Catch ArrayIndexOutOfBoundsException in SwingWorker and Executor Threads?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-19 20:08:10173browse

How to Catch ArrayIndexOutOfBoundsException in SwingWorker and Executor Threads?

Problem with ArrayIndexOutOfBoundsException in SwingWorker and Executor

Problem description

Using Executor and SwingWorker When performing multi-threaded operations, the subject encountered an ArrayIndexOutOfBoundsException, but after commenting out the statements that would cause the exception in the code, the exception did not appear again. The questioner wants to know how to catch such an exception.

Answer

To catch ArrayIndexOutOfBoundsException, you can rethrow the exception from Future#get() in SwingWorker's done() method.

@Override
protected void done() {
    try {
        get();
    } catch (InterruptedException | ExecutionException ie) {
        ie.printStackTrace();
    } catch (IllegalStateException is) {
        is.printStackTrace();
    }
}

Modified code snippet

// ...

@Override
protected void done() {
    if (str.equals("StartShedule")) {
        try {
            get();
        } catch (InterruptedException | ExecutionException ie) {
            ie.printStackTrace();
        } catch (IllegalStateException is) {
            is.printStackTrace();
        }
    }
}

Full code

The complete code is as follows:

// ...

@Override
protected void done() {
    if (str.equals("StartShedule")) {
        try {
            get();
        } catch (InterruptedException | ExecutionException ie) {
            ie.printStackTrace();
        } catch (IllegalStateException is) {
            is.printStackTrace();
        }
    }
}

// ...

After using this modification, the code that causes the exception can be captured even if it is not commented out. ArrayIndexOutOfBoundsException.

The above is the detailed content of How to Catch ArrayIndexOutOfBoundsException in SwingWorker and Executor Threads?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn