有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java IllegalStateException和NoTouchElementException之间有什么区别

我想在下面的代码中抛出一个错误

if (!this.isAttached(object.getElementById(Name))) 
{
     throw new NoSuchElementException(Name);
}
this.clickElement(object.getElementById(Name));

哪一个是最适合抛出的异常:NoSuchElementExceptionIllegalStateException


共 (1) 个答案

  1. # 1 楼答案

    您将从文档中了解更多信息:

    NoSuchElementException Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

    IllegalStateException Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

    在您的情况下,抛出NoSuchElementExceptionIllegalStateException甚至Exception的异常并不重要,因为它只抛出一条消息,而不是真正的异常

    如果您阅读了任何异常的构造函数,您可以理解:

    public AnyException(String s)

    Constructs an AnyException with the specified detail message. A detail message is a String that describes this particular exception.