Reputation:
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;
}
Upvotes: 2
Views: 108
Reputation: 22446
There are three options to choose from, depending on your scenario:
Edit: Another 2 options:
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).
Upvotes: 2
Reputation: 35557
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();
}
}
Upvotes: 0
Reputation: 2068
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.
Upvotes: 2
Reputation: 1769
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.
Upvotes: 1
Reputation: 252
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;
}
Upvotes: -2