2

Is there any solution i can break a running method which is supposed to return an int[] or whatever but !without! any return value. I thought that might work with some exception but i didn't find a propper way. To be more specific i want something which tries to find out if a certain field of an object was set and if yes return it and if no returns a message which tells me that the input wasn't made so far. something like this:

public int[] returnArray(){
       if(array_was_set==true) return the array;
       else show message that it wasnt set and quit the method without any return value;
   }

5 Answers5

2

One way of doing that, return null and make the caller decide , if the caller gets a nun-null (or maybe a non-empty) array it will process it in some way and if the caller get an empty or null array it could print a message.

I would recommend against using exceptions as a substitute for return values see this question to know more about when to throw an exception.

Community
  • 1
  • 1
Yazan Jaber
  • 2,068
  • 25
  • 36
2

There are three options to choose from, depending on your scenario:

  1. Use return value of null (and document it)
  2. Throw an exception with a detailed message. I would use this version only for exceptional cases such as illegal API usage or a logical error situation(bug).
  3. Return a wrapper class, containing both a return value and some other message, when relevant

Edit: Another 2 options:

  1. Use polymorphism - Return type can be Result, and concrete subclasses can be NoResult and DataResult.
  2. Instead of returning null, return a constant value defined as:

    static final NO_RESULT = new int[0];

Later you can check the returned value against it (using == condition).

Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78
  • 1
    I particularly like empty arrays/collections for this sort of thing because often you have to make no other adjustment, if the array is looped over to get the results the loop simply quits – Richard Tingle Jan 21 '14 at 14:15
  • I agree with @RichardTingle on returning an empty int[]. It explicitly fits the contract defined by the method (otherwise you always need to check null before accessing the array) and makes unit testing easier. Then the caller, who probably has better information as to whether this is an exception or not, can decide if the empty array is an error state or not. – tfandango Jan 21 '14 at 14:37
  • @tfandango: When applicable, I prefer this method as well. However, It doesn't always meet the method contract. In some cases it can create ambiguity, when an empty array is a legitimate data. – Eyal Schneider Jan 21 '14 at 14:39
  • @RichardTingle that is a good point! In other words, an error and no-results are indistinguishable. – tfandango Jan 21 '14 at 14:51
  • @tfandango Looking at it more closely I agree, I thought this was a "looking for something and returning a collection of it" but this is actually looking to see if a single concrete object exists – Richard Tingle Jan 21 '14 at 14:53
1

You should be able to do it by raising an exception. Just use the message in the exception's constructor.

However, exceptions are relatively expensive and if this isn't really an error condition you should consider doing something else, such as returning null to indicate there is nothing to return.

Mark Wagoner
  • 1,729
  • 1
  • 13
  • 20
0

Yes better way is use Exception

example

public static void main(String[] args) {
    try {
        new Result().returnArray(false) ;
    } catch (Exception e) {

    }
}

.

public int[] returnArray(boolean input) throws Exception {
    if(input) {
        return new int[]{1};
    }
    else {
        System.out.println("Not match");
        throw new Exception();
    }
}
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
-2

When you declare in the method signature that it is returning a data type then it must have a return statement which returns that specific type value. Otherwise you will get compile-time error. The only exception when a method can avoid return statement even though it has return type is when there is an infinite loop or an exception is thrown. Otherwise return statement is compulsory. Coming to your question, you can easily achieve what you are doing. If you want to terminate at a particular point as per your requirement just say, return null;

It will work for all the data types except for primitive types in which case you need to do type casting to Wrapper class types appropriately.

public int[] returnArr()  {
   if(some condition)
     return SomeIntArray;
   else
     return null;
}

public int returnInt()  {
   if(some condition)
       return 2;
   else
       return (Integer)null;
}
Perefexexos
  • 252
  • 1
  • 8
  • 2
    The second method will throw a NullPointerException if `some condition` is false. @EyalSchneider it compiles but generates an 'unnecessary cast' warning. – Njol Jan 21 '14 at 13:54
  • I thought there might have been an exception for this but on the other hand i prefer to keep it simple, so that helps. Thank you all guys. –  Jan 21 '14 at 13:59
  • 1
    You can return null and use that as an indication that it wasn't set. – Perefexexos Jan 21 '14 at 14:00
  • 1
    I correct myself - the returnInt() method *does* compile (with the cast), but it's useless - it produces a NullPointerException when trying to unbox the Integer into an int. – Eyal Schneider Jan 21 '14 at 14:04