Christopher Baldwin
Christopher Baldwin

Reputation: 347

Why does this throw an InterruptedException?

enter image description here

This code should compile, should it not? What am I doing wrong? I would like the code to briefly pause before displaying each number in the array.

public static void median(int odd[]) throws InterruptedException {

    Arrays.sort(odd);

    for (int i = 0; i < odd.length; i++) {
        System.out.println(odd[i]);
        Thread.sleep(500);
    }
    System.out.println("The median number of the previous list of numbers is: " + odd[5]);
}

Upvotes: 0

Views: 241

Answers (4)

JoeC
JoeC

Reputation: 1850

It's better to use try catch block for Thread.sleep

Remove the throw exceptions and change

Thread.sleep(500);

to

try{Thread.sleep(500);}catch(Exception e){}

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279990

I'm assuming that in your main you have something like

public static void main (String[] args) {
    int[] array  = new int[X];
    ...// populate array
    median(array);
}

Because median is a method declared as throwing a checked exception, you must either catch the Exception or rethrow it.

public static void main (String[] args) {
    int[] array  = new int[X];
    ...// populate array
    try {
        median(array);
    } catch (InterruptedException e) {
        // handle it
    }
}

or

public static void main (String[] args) throws InterruptedException {
    int[] array  = new int[X];
    ...// populate array
    median(array);
}

Upvotes: 2

Makoto
Makoto

Reputation: 106440

I'm not entirely convinced that the exception is thrown, but the reason you have to either declare it to be thrown, or catch it yourself, is due to it being a checked exception.

Because InterruptedException is declared as part of the signature of the method, you must address it in some way.

Upvotes: 0

iWumbo
iWumbo

Reputation: 135

Use Timer or TimerTask instead of making the thread sleep.

Upvotes: 0

Related Questions