I would truly appreciate if someone could help me to understand why my code won't work the way it should:
I'd like to catch the exception when the index being tested (in the main class) is out of bound from my ArrayList in the getter method.
It should behave like: if the index (testing using 8) is out of bound from the ArrayList (length of 5), then the program will not get any value and print out statement saying Will Skip, and keep moving to the next line. If the index is not out of bound, return the value from the ArrayList.
What I have below works only when there is a "return" value in the Catch(). I know it is because the getter is asking to return a double. But I don't know how to fix this to behave the way stated above. Thank you so much!
Main Driver class for testing:
TestValue object = new TestValue();
System.out.println("The value is " + object.getListValue(8));
...other methods like print values, set new values etc.
TestValue class:
public double getListValue(int index) {
try {
listValue.get(index);
while (index <0 || index >= listValue.size()) {
}
}
catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
System.out.println("Can't get value. Will skip this request. ");
return listValue.get(0); // I don't want to return any values
}
return listValue.get(index);
}
This is because the definition of your method was public double,
you have to return a double unless you throw an exception.
If you really don't want to return a value, you can return 0.0.
Related
I have written this simple code to check weather a binary heap is empty or not. I have problem with return. It can not be: null, void, or nothing; It should return something int, but I don't know what. So, what should I put there, if I want to keep this code simple? (I mean not using Integer class or java.lang.Integer).
public int getMinimum() {
if (isEmpty()) {
System.out.println("Heap is empty");
return;
} else
return data[0];
}
throw a exception for invalid value and handle it when calling
public int getMinimum() throws Exception {
if (isEmpty())
throw new Exception("Heap is Empty");
else
return data[0];
}
and when getting minimum
try{
int i = getMinimum();
System.out.println("Minimum is :" + i);
}catch(Exception e){
System.out.println(e.getMessage());
}
I can only help with elimination... java is not magic. If you declare your function to return an "int", then the compiler will make you return an int.
Which leaves limited options:
1) throw an exception, and teach your users to use it in combination with 'isEmpty()', e.g.:
if(theHeap.isEmpty()) System.out.println("empty");
else System.out.println(theHeap.getMinimum())
2) use that Integer which you didn't like (I'm guessing, for performance reasons?)
3) find some int value that's not likely to be present in the data, e.g. perhaps you don't expect your heap to ever hold Integer.MIN_VALUE.
If your heap contained doubles, i'd recommend NaN.
That's all that's available in the java syntax, sorry it's not ground braking...
int is a primitive and therefore needs to have a value.
If you really want to solve it like this, you need to specify a certain int value that would never appear in the heap. You could also try throwing an exception when heap is empty.
we can simply declare it is "Integer" instead of "int", so we can return "null", as well.
public Integer getMinimum(){
if(isEmpty())
return null;
else
return data[0];
}
If someone calls my method, I want to defensively deal with the problem. Usually I just return null.
I decided to implement a try catch but it looks like I just end up returning null anyway.
Can I write my try catch in such a way that at the end of method it doesn't return null?
Sample code, using peek on a Stack class.
public T peek()
{
T temp = null;
try
{
temp = array[size];
}
catch(Exception e)
{
}
return temp;
}
When called with an empty stack. It will return null.
So should I even bother with the try catch for this kind of case? I am tempted to do this:
if(isEmpty())
return null;
If the stack is not empty I want to return the element. If the stack is empty then can I avoid returning null if I use the try-catch?
This is how I would approach the problem. By throwing an exception in the peek function, putting the duty of handling that exception in the caller. Why? Because I want an error to cause an explosion as big as possible. The peek method also became smaller. Also as you already agree on, returning null is lame.
public T peek() throws IndexOutOfBoundsException
{
return array[size];
}
and
try
{
T top = thestack.peek();
/* Do something with that object */
}
catch(IndexOutOfBoundsException e)
{
/* Do something else */
}
The method has to return something or throw an Exception. If you have an unbounded generic type, then things like null object patterns can't be used, so the options are returning null, returning something that contains T like Optional<T>, or throwing an Exception.
If you don't like the safety of null, you can use Optional, either from Java 8 or a library. Checked exceptions have a similar safety but are inappropriate here.
It's hard to imagine the array[size] throwing an Exception, unless array is null or size is outside the length of array. So, you could do something like this -
if (array != null && array.length > size) {
return array[size - 1]; // assuming your size starts at 1
}
return null; // need to return something, if not null you need an option type.
Edit
Or, using an Option monad - and something like,
if (array != null && array.length > size) {
return new Some<T>(array[size - 1]); // assuming your size starts at 1
}
return new None<T>();
I have a class with a method get done in this way:
public int get(int i) throws ArrayIndexOutOfBoundsException {
if(i < numElements)
return elements[i];
else
throw new ArrayIndexOutOfBoundsException("");
}
Now I have to make sure that this method works.
I do a test to test the get method on an array of length 0.
So in main I wrote:
try {
IntSortedArray r3 = new IntSortedArray(0); //I create an array of length 0
if( **???** ) {
System.out.println("OK");
}
else {
System.out.println("FAIL");
}
} catch(Exception ecc) {
System.out.println(ecc + " FAIL");
}
What do I put as a condition of the if? Thanks
The class IntSortedArray:
private int[] elements;
private int numElements;
public IntSortedArray(int initialCapacity) {
elements = new int[initialCapacity];
numElements = 0;
System.out.println("Lunghezza dell'array: " + elements.length);
}
You can do
try {
IntSortedArray r3 = new IntSortedArray(0);
r3.get(0);
fail();
} catch(ArrayIndexOutOfBoundsException expected) {
}
Okay. So you've got at least two different things to test here:
If the object can be constructed reasonably, and
If you can retrieve an element from the object with respect to its size.
From that, given your constructor, you could construct your object with a non-negative number, as well as a negative number. Further, you could also retrieve a non-negative element in bounds of your array, a non-negative element out of bounds to your array, and a negative element (which is definitely out of bounds) to your array.
There's about five test cases here. I'll use JUnit as an example for you to test the case in which you're trying to pull an element out of your wrapped array, and it is out of bounds. It will pass incidentally, since you're only doing one-half of the check; attempting to index into an array position that is equal to the length is also out of bounds.
// Test will pass due to exception being thrown.
#Test(expected = ArrayIndexOutOfBoundsException.class)
public void getWithElementOutOfBounds() {
IntSortedArray r3 = new IntSortedArray(0);
rt.get(0);
}
With the expected portion of the #Test annotation, you can expect certain exceptions to be thrown without needing to provide a conditional, or a try-catch block.
As I was reading my AP java book I stumbled upon this section that made no sense to me:
...The getBalance method simply returns the current balance. A return statement obtains the value of a variable and exits the method immediately. The return value becomes the value of the method call expression. The syntax of a return statement is:
return expression;
or
return; // Exits the method without sending back a value
Why would you want to have a return statement and "exit the method without sending back a value" if you could just make it void?
***Note: Sorry if this may be too subjective. I just couldn't understand the point and the book doesn't explain it.
The return keyword doesn't need to be at the end. For example:
public static void print42(int[] numbers) {
for(int i=0; i<numbers.length; i++) {
if (numbers[i] == 42) {
System.out.println("has 42");
return;
}
}
System.out.println("no 42");
}
It can't just use a break, as that would print both strings.
This is kind of subjective. I'm old school, I believe in one entry and exit point for all methods/functions, but...
If you have a method with a void return type and if you had reached a point in your logic which would dictate that no further processing should take place, you could call return; to force the execution to return to the calling method at this point, foregoing any further execution of the method.
It would be the same as using something like return x; in the middle of a method body that had an expected return type (of whatever x is)
It's a little like using break to break out of a loop prematurely, except you're breaking out of the method before the execution gets to the end.
There are some situations where once you've verified something inside a void function, it makes sense to exit it immediately. For example:
public static void checkIfStringInList(List<String> searchList, String findString) {
for( String thisSearchString : searchList ) {
if( findString.equals(thisSearchString) )
return;
}
throw new Exception("String " + findString + " not found in list");
}
A method declared as void can exit with a return; this is just a shortcut for early termination. A method with a non-void return type must return a value of the right type, you can not have a method return "nothing" if it has a non-void return type.
If your method has a void return type, then the return statement is optional. You might want to use it anyway if, for instance, you wanted to stop execution in certain cases.
If the return type is not void, then using return; without an argument will give you a compile error.
In java if a method has a return type in its signature, you must return an object of that type or null before exiting the method.
for example
public A foo(boolean val){
A obj=null;
if (val){
obj=new A();
obj.setSomeAttribute();
}
return obj;
}
You can not compile source code if you just code "return;"
I read code from one book and have this method:
public int getScore(String name) {
try {
//some code here
return score;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
Why this method in catch returns -1? Why not 5? Is that some convention?
-1 is a standard error code when the caller expects a positive int
but really in that case a wrapped RuntimeException or a more specific one would have been much better
I'm assuming the author uses this code to make sure something gets returned, and the caller of getScore can check to see if a score was correctly called.
In code:
int theScore = getScore("My Name");
if(theScore == -1) {
// Oh no, there was an error!
}
We can use the check for -1 to make sure that the code knows when getScore fails.
Why method returns -1?
Because it is very poorly designed to do so on any exception. The method would have been better designed by declaring it to throw the exception(s) of interest and specifically by not catching all the RuntimeExceptions as well.
You are the one choosing what you want to return as you are the only one who knows how you want to handle that returned value. I personally use -1 too when I want to detect an error, and I know a lot of people doing the same.
The reason they picked -1 instead of 5 is because -1 is not a feasible score to return from the getScore method. Therefore, when you call the function, you can easily check if it was -1 returned or not.
If it was a function that could realistically return -1 for a successful run, -1 would be a poor choice of a flag indicator. A more appropriate choice, then, might be -9999 or something ridiculous.
The first problem is we don't know what the exceptions are. Catching every exception is a very poor decision. Those exceptions were thrown for a reason so you would know exactly what went wrong and can deal with it appropriately.
Bad:
public int getScore(String name) {
try {
int score = scores.getScoreForName(name);
return score;
} catch (Exception e) { // catches everything
e.printStackTrace();
return -1;
}
}
Marginally better...
public int getScore(String name) {
try {
int score = scores.getScoreForName(name);
return score;
} catch(NameNotFoundException) {
e.printStackTrace();
return -2; // now we know what happened, not just a general error
} catch (Exception e) { // catches everything
e.printStackTrace();
return -1; // generally error
}
}
Much better:
/**
* Get the score for a given name. Will throw a runtime exception if the
* name doesn't exist.
* #param name The name to get the score for
* #return the score for the name
* #throws NameNotFoundException if the name doesn't exist in the database.
*/
public int getScore(String name) {
return scores.getScoreForName(name);
}