抛出一个UnsupportedOperationException异常 [英] Throwing an UnsupportedOperationException

查看:178
本文介绍了抛出一个UnsupportedOperationException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以一个方法描述如下:

So one of the method descriptions goes as follows:


public BasicLinkedList addToFront(T data)此操作无效
为排序列表。将使用消息排序列表的无效操作
生成UnsupportedOperationException。

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."

我的代码如下所示:

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;
}

这是正确的做法吗?我刚刚使用 println()打印出消息,但有不同的方式来生成消息?

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?

推荐答案

您不想在方法中捕获异常 - 重点是让调用者知道不支持该操作:

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

这篇关于抛出一个UnsupportedOperationException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆