简体   繁体   English

Java错误:未报告的异常?

[英]Java Error: Unreported exception?

I've got the following method: 我有以下方法:

public T peek() throws StackEmptyException {
    Node<T> tracker = head; 
    while(tracker.getNext() != null) {
        tracker = tracker.getNext(); 
    }
    return tracker.getItem(); 
}

The problem is that when I try to do something like 问题是当我尝试做类似的事情时

int firstOne = stack.peek(); 

I get an unreported exception StackEmptyException and I have no idea what I'm doing wrong at this point. 我得到一个unreported exception StackEmptyException ,我不知道我在这一点上做错了什么。 The StackEmptyException has been made in a separate class. StackEmptyException是在一个单独的类中完成的。 Am I suppose to have this class extend that new exception class I made? 我想这个类扩展了我制作的新异常类吗? So confused. 如此迷茫。 Thoughts guys? 想家伙?

Since StackEmptyException is an checked exception (which you shouldn't do in first place), you should handle that exception when invoking the peek() method. 由于StackEmptyException是一个已检查的异常 (您不应该首先执行此操作),因此在调用peek()方法时应该处理该异常。 The rule is, either you should handle the exception or declare it to be thrown. 规则是,您应该处理异常或声明它被抛出。

However, I would take a step back and change StackEmptyException to an Unchecked Exception . 但是,我会退后一步,将StackEmptyException更改为Unchecked Exception Then you wouldn't need to handle it or declare it as thrown. 然后你不需要处理它或声明它被抛出。

Checked exceptions (ie, a class which extends Exception but not RuntimeException or Error ) thrown by a method should be handled by this method's caller, recursively so. 由方法抛出的已检查异常(即,扩展Exception但不是RuntimeExceptionError )应该由此方法的调用者以递归方式处理。

Here you have .peek() which throws, say, exception class E (bad name, but this is for illustration). 在这里你有.peek() ,它会抛出异常类E (坏名称,但这只是为了说明)。 You must do one of the following in a foo() method which calls .peek() : 您必须在调用.peek()foo()方法中执行以下操作之一:

  • catch it, or catch它,或者
  • throw it again. 扔掉它。

That is, either: 那就是:

// catch
void foo()
{
    try {
        peek();
    } catch (E e) {
       // something
    }
}

or: 要么:

// throw
void foo() throws E
{
    peek();
}

You could even rethrow it: 你甚至可以重新抛出它:

// catch then rethrow
void foo() throws E
{
    try {
        peek();
    } catch (E e) {
        // something, then
        throw e;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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