I don't understand why the catch is not executed.
@Override
public void remove(int value) throws NoSuchElementException {
ListItem index = head;
System.out.println("value " value);
try {
if (contains(value) == true) {
System.out.println("Nö");
if (head == tail) {
tail = null;
} else if (head.value == value) {
head = head.next;
}
while ((index.next != null) && (index.next.value != value)) {
index = index.next;
}
if (index.next == null) {
index = null;
} else if (index.next.value == value) {
index.next = index.next.next;
}
}
} catch (NoSuchElementException e) {
System.out.println("HEllo");
throw new NoSuchElementException("No such Element.");
}
// System.out.println("HEllo 2");
}
I thought the Exception is thrown if I do not fulfill my try, I achieve this if I have
if (contains(value) == true )
But even if this is false it does not work.
CodePudding user response:
Exceptions in Java are generally thrown
when there are unexpected behaviors or errors.
In the try-catch
block you have given, the catch
block will only execute when the NoSuchElementException
exception is thrown somewhere within the try
block.
Hence, just because the code reaches the end of the try
block without "fulfilling" your if statement
condition, does not mean the catch
block you have written will excecute.
You can learn more about Exceptions and the try-catch block
in Java from here and here.
CodePudding user response:
As Yağız Can Aslan mention above the catch block will only be trigerred if an NoSuchElementException
is thrown in your try block
If you want to propagate the exception to the calling method of remove
you could simply throw the exception yourself if your condition is not fulfilled :
@Override
public void remove(int value) throws NoSuchElementException {
ListItem index = head;
System.out.println("value " value);
if (contains(value) == true) {
System.out.println("Nö");
if (head == tail) {
tail = null;
} else if (head.value == value) {
head = head.next;
}
while ((index.next != null) && (index.next.value != value)) {
index = index.next;
}
if (index.next == null) {
index = null;
} else if (index.next.value == value) {
index.next = index.next.next;
}
} else {
throw new NoSuchElementException("No such Element.");
}
}
}
The exception will be thrown to the calling method in wich you will have to either make a try/catch
or re-thrown the exception upward again.