繁体   English   中英

如何执行异常

[英]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 )

但即使这是错误的,它也不起作用。

Java 中的异常一般在出现意外行为或错误时thrown

在您提供的try-catch块中,只有在try块中的某处抛出NoSuchElementException异常时, catch块才会执行。

因此,仅仅因为代码到达try块的末尾而没有“满足”您的if statement条件,并不意味着您编写的catch块将执行。

您可以从此处此处了解有关异常和 Java 中的try-catch block的更多信息。

正如 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM