-1

I'm implementing a fixed sized Queue in java which uses a constant size ArrayList as underlying container, where my front() method is supposed to return front element of Queue .

   public T front(){


        try{
            if(isEmpty())
                throw new Exception("Queue is Empty- can't return Front element.");
            return arrayList.get(frontIndex);

        }catch (Exception e){
            System.out.println(e);
        }

    }

By coding in above way , I want front() to return a value only if no Exception is thrown ,however as expected compiler show me "Missing return statement." So , is there any way I can make the function return only if no Exception is thrown.

charany1
  • 751
  • 1
  • 9
  • 25
  • If the method has a non-`void` return type, you *have* to either return a value, or throw an exception. There is no other alternative. What do you want to do of those two options? – Erwin Bolwidt Jul 11 '15 at 07:50

4 Answers4

3

Since you are catching the exception in the code the compiler shows that missing return statement error.

You can implement the function Like this :

public T front() throws Exception {

    if(isEmpty()) {
       throw new Exception("Queue is Empty- can't return Front element.");
    }

    return arrayList.get(frontIndex);
}

and finally handle the exception at calling function/client

ΔȺȾΔ
  • 21,571
  • 10
  • 52
  • 80
Rishi Ahuja
  • 116
  • 4
1

I want front() to return a value only if no Exception is thrown

Rhetorical question: What do you want to return if an Exception is thrown?

Here is the problem. You have declared front() as returning something (an instance of T). That means that there are two relevant ways1 to terminate a call to front():

  • It can terminate normally by returning something that conforms to the type T.

  • It can terminate abnormally by throwing an unchecked exception.

You can't return "nothing", because front() has to return a value.

You can't throw a checked exception (like Exception) because front() is not declared as throwing any exceptions.


So what can you do?

  • You can change the method signature so that SomeException is thrown, where SomeException descends from Exception. (Throwing Exception is a really bad idea ...)

  • You can change throw new Exception to throw new SomeException, where SomeException is descended from RuntimeException.

  • You can return null assuming that T is a reference type. (It will be if T is a type parameter.)


1 - Actually, there are a couple of other ways, but they are not useful in this context. For example, you could call System.exit(int) and terminate the JVM. (And there are ways of structuring the code so that you don't need a (redundant) return or throw following the exit call. Hint: infinite loops don't need to return.)

Stephen C
  • 632,615
  • 86
  • 730
  • 1,096
  • Even if you call `System.exit(int)` you still have to return a value or throw an exception; the compiler doesn't know that the program flow stops after a call to `System.exit(int)`. – Erwin Bolwidt Jul 11 '15 at 07:52
  • Rhetorical I can return anything of T type or null even when an Exception will be throw – ceph3us Jul 11 '15 at 08:06
  • thanks , your rhetorical question made things clear for me , I appreciate that! – charany1 Jul 11 '15 at 08:12
  • @TomaszBest - you missed the emphasis on the word "want". That was the point I was trying to make. – Stephen C Jul 11 '15 at 10:25
  • @stephen-c i don't see third possibility in your explanation: 1) throw ex, 2) return object T type or null 3) throw ex & return T type object or null see at my answer what i mean – ceph3us Jul 11 '15 at 11:31
  • @TomaszBest - Hint ... infinite loop. Bear in mind that we are talking about code that won't be executed in an "edge case" solution, etc ... – Stephen C Jul 11 '15 at 23:12
0

Why do you use the exception at all if you are catching it afterwards? You have to either return T or throw an exception. But the method doesn't throw an exception since you are catching it. Is it not easier to do just that:

   public T front() throws SomeException{ // if SomeException is checked you need to declare it
        if(isEmpty())
            throw new SomeException("Queue is Empty- can't return Front element.");
        return arrayList.get(frontIndex);
    }

You should also use a more specific exception, not Exception.

user140547
  • 6,545
  • 2
  • 21
  • 63
  • 1
    The exceptions are meant to be caught he should throw an Error – ceph3us Jul 11 '15 at 07:47
  • Exceptions can be caught, but usually they are caught by the caller of the method, and not in the method itself – user140547 Jul 11 '15 at 07:52
  • What distinguishes an exception from error? The error should never be caught – ceph3us Jul 11 '15 at 07:57
  • @TomaszBest ,well , Exceptions are mechanism to handle abnormal condition without let the program terminate abruptly , so rather than an Error , throwing an Exception suits my issue. – charany1 Jul 11 '15 at 08:03
  • @user140547 , can you give some reason as to why exceptions are usually not to be caught within the method in which they are generated? – charany1 Jul 11 '15 at 08:05
  • @charany1: Well if you throw an exception, the caller of the method can react to it. But if you catch the exception in the method itself you use the exception for control flow which is usually not a good idea. In this case, it even complicated the method. See http://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control – user140547 Jul 11 '15 at 08:12
  • @charany1 if u don't plan to catch an exception u throw an error. What sense got to throw here ex rather return null? U got assumption that yr data are irrelevant to continue or not? – ceph3us Jul 11 '15 at 08:24
  • Sense of throwing ex is to handle it by exception handler anyway it will terminate program. Catching ex in the same method is a way to handle it without involving call stack and got no purpose of dealing with errors. – ceph3us Jul 11 '15 at 08:40
0

this "example" shows a possibility when u can throw an exception and return value

private boolean throwExReturnValue() throws NullPointerException {

    try {

       throw new NullPointerException("HAHA");
    }

    finally {

        return true;
    }
}

private void ExceptionHanler() {

     boolean  myEx; 

     try { 

       myEx = throwExReturnValue(); 

       /** code here will still execute & myEx will have value = true */

     } catch (Exception ex) {

       /** will execute or not (depending on VM) even we throwed an exception */

     }

    /** code will still execute */

}

EDIT:

i tried this with two different VM and to my surprise one is throwing Exception second is skipping the catch block and execute code so it's depending on VM implementation

ceph3us
  • 6,591
  • 2
  • 34
  • 39