简体   繁体   English

抛出UnsupportedOperationException

[英]Throwing an UnsupportedOperationException

So one of the method descriptions goes as follows: 因此,方法描述之一如下:

public BasicLinkedList addToFront(T data) This operation is invalid for a sorted list. public BasicLinkedList addToFront(T data)此操作对排序列表无效。 An UnsupportedOperationException will be generated using the message "Invalid operation for sorted list." 将使用消息“排序列表的无效操作”生成UnsupportedOperationException。

My code goes something like this: 我的代码是这样的:

public BasicLinkedList<T> addToFront(T data) {
    try {
        throw new UnsupportedOperationException("Invalid operation for sorted list.");
    } catch (java.lang.UnsupportedOperationException e) {
        System.out.println("Invalid operation for sorted list.");
    }
    return this;
}

Is this the right way of doing this? 这是正确的做法吗? I just printed out the message using println() but is there a different way to generate the message? 我刚刚使用println()打印出消息,但是有不同的方法来生成消息吗?

You don't want to catch the exception in your method - the point is to let callers know that the operation is not supported: 您不希望在方法中捕获异常 - 关键是让调用者知道不支持该操作:

public BasicLinkedList<T> addToFront(T data) {
    throw new UnsupportedOperationException("Invalid operation for sorted list.");
}

You could rewrite your code to be like this 您可以将代码重写为这样

public BasicLinkedList<T> addToFront(T data) throws UnsupportedOperationException {
    if (this instanceof SortedList) {
        throw new UnsupportedOperationException("Invalid operation for sorted list.");
    }else{
        return this;
    }
}

That basically accomplishes what you're asking. 这基本上完成了你所要求的。

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

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