[英]How to execute a Exception
我不明白为什么不执行 catch。
@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");
}
我认为如果我没有完成我的尝试就会抛出异常,如果我有
if (contains(value) == true )
但即使这是错误的,它也不起作用。
正如 Yağız Can Aslan 在上面提到的那样,只有在您的 try 块中抛出NoSuchElementException
时才会触发 catch 块
如果你想将异常传播到remove
的调用方法,如果你的条件不满足,你可以简单地自己抛出异常:
@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.");
}
}
}
异常将被抛出到调用方法中,您将不得不进行try/catch
或再次向上抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.