Throwing an UnsupportedOperationException

佐手、 提交于 2019-12-09 16:39:39

问题


So one of the method descriptions goes as follows:

public BasicLinkedList addToFront(T data) This operation is invalid for a sorted list. An UnsupportedOperationException will be generated using the message "Invalid operation for sorted list."

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?


回答1:


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.");
}



回答2:


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.



来源:https://stackoverflow.com/questions/15329579/throwing-an-unsupportedoperationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!