Friday, August 5, 2022

[FIXED] How to return a value from try, catch, and finally by using condition?

Issue

My get() method is being marked with a red line, it tells me

this method must return a result of type char

public char get() {
    mutex.lock();
    char c = buffer[out];
    try {
        while (count == 0) {  
            okConsume.await();
        }
        out = (out + 1) % buffer.length;
        count--;
        System.out.println("Consuming " + c + " ...");
        okConsume.signalAll();
        return c;
    }catch(InterruptedException ie) {
        ie.printStackTrace();
    }finally {
        mutex.unlock();
    }
    
}

Solution

Your code should cover all the possible scenario. Now it doesn't because you're not returning from the method if exception occur.

The return statement placed inside the try will be unreachable in case of exception.

For more information on Exception-handling, I suggest to have a look at this tutorial.

There are two ways to fix it:

  • place return statements in both try and catch blocks;
    public char get() {
        mutex.lock();
        char c = buffer[out];
        try {
            // some code
            return c;
        } catch (InterruptedException ie) {
            ie.printStackTrace();
            return c;
        } finally {
            mutex.unlock();
        }
    }
  • place the return statement after the finally block;
    public char get() {
        mutex.lock();
        char c = buffer[out];
        try {
            // some code
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        } finally {
            mutex.unlock();
        }
        return c;
    }


Answered By - Alexander Ivanchenko
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.