PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 5, 2022

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

 August 05, 2022     conditional-statements, exception, java, return-value, try-catch     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing