unsupportedoperationexception java что это

Все зло UnsupportedOperationException в примерах

Привет, сегодня я хотел бы поговорить о культуре проектирования. Многие программисты (особенно джуниоры) боятся создать лишний класс, интерфейс и т.п… Причин тому, я уверен, немало, однако эта тема выходит за рамки этого поста. Но как раз из-за этого появляются очень интересные проблемы, о которых я хотел бы сегодня рассказать. Если я тебя заинтриговал — добро пожаловать под кат.

Как пример возьмем JDK интерфейс Iterator.

Этот код взят именно из JDK 1.8 не просто так. Дело в том, что в JavaDoc’е к методу remove сказано, что он может кидать UnsupportedOperationException, в случае, если реализация интерфейса его не поддерживает. И на мой взгляд это большая проблема. Конечно, я понимаю, что в JDK она вызвана поддержкой обратной совместимости и уже ничего с этим не сделаешь, ничего не сломав.

Я долго думал, как проиллюстрировать эту проблему. И вот, я обратил свое внимание на нее, когда я приехал в гости к другу. Пока друг удалился в кухню за пивом соком, я решил включить кондиционер, он был такой же, как и у меня дома и я без вопросов взял пульт и начал клацать. Не работает. Переподключил конциционер к сети, проверил батарейки в пульте, подошел вплотную — и нечего, мой любимый турбо-режим не работает и все, о чем я и пожаловался другу, когда он вернулся. Но тут-то меня и ждал сюрприз: «А в этой модели нет никаких турбо-режимов», — хладнокровно ответил мне друг. «Как так, вот же кнопка „turbo“», — показываю я другу пульт.

Приблизительно такие же чувства я испытываю когда мне прилетает вот такой вот UnsupportedOperationException. На мой взгляд, эта проблема должна решаться простой иерархией интерфейсов, и если с пультами проблема вызвана нерентабельностью, но ведь у нас таких проблем нет 😉

Спасибо за внимание.
Буду рад коментариям и объективной критике.

Источник

Java:UnsupportedOperationException

In today’s article we’ll examine the UnsupportedOperationException in more detail, beginning with a dive into where it sits in the overall Java Exception Hierarchy. We’ll also go over a handful of functional code samples illustrating how UnsupportedOperationExceptions can be thrown in the standard Java library, along with how you might consider using them in your own code, so let’s get started!

The Technical Rundown

All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

This code sample also uses the Book.java class, the source of which can be found on GitHub.

It also uses the Logging.java class, the source of which can be found on GitHub.

When Should You Use It?

As an example, imagine that you need a collection that is unmodifiable (i.e. immutable ). To accomplish this you might look to the AbstractList class. Since this is an abstract class we must imeplement it ourselves in our own class, so we’ll do so in the DefaultAbstractList class:

Since AbstractList is a parent class of our DefaultAbstractList class, we’re able to specify it as the expected parameter type of our method, allowing us to pass other class instances that extend AbstractList later on. Otherwise, the functionality of addBookToList(. ) is fairly simple: We start by outputting the book info and list class we’re attempting to add it to. Then we call the add(int index, E element) method of the list parameter. Finally, we output the modified list information, including the newly added element.

To test this out our Main.main(. ) method creates a new DefaultAbstractList instance, then attempts to add a new Book instance to it via addBookToList(. ) :

If you’re familiar with using AbstractLists already, you may see what’s coming. Executing the test code above produces the following output:

Here we catch our first UnsupportedOperationException which, unfortunately, fails to provide much useful information since there’s no associated error message. A bit of digging reveals that the issue is that, while the AbstractList includes the add(int index, E element) method, it intentionally throws an UnsupportedOperationException when invoked. This is because calling an add(. ) method of any collection indicates that the collection should be changeable ( mutable ), which we did not plan for in our DefaultAbstractList class.

To resolve this we’ll create another class that is designed to handle mutable lists, MutableAbstractList :

This time we have no trouble invoking the add(int index, E element) method to add our new Book instance, which results in the expected output showing the book being added to the collection:

That’s cool and we’ve now seen how the standard Java library sometimes throws UnsupportedOperationExceptions to indicate invalid method calls. However, let’s look briefly at how we might throw an UnsupportedOperationException in our own code, under the right circumstances. To accomplish this we’ll look at our last custom class, aptly named ImmutableList :

Although subtle, we have to use a slightly different addBookToList(. ) method signature than before, since ImmutableList doesn’t extend the AbstractList class that our previous examples did. Attempting to use the addBookToList(Book book, AbstractList list) method signature with an ImmutableList argument would result in a compilation error, so we’re using this second method signature instead:

Otherwise, our call to addBookToList(. ) is much the same as before:

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices! Try Airbrake free for 30 days.

Monitor Your App Free for 30 Days

unsupportedoperationexception java что это. Смотреть фото unsupportedoperationexception java что это. Смотреть картинку unsupportedoperationexception java что это. Картинка про unsupportedoperationexception java что это. Фото unsupportedoperationexception java что это

Discover the power of Airbrake by starting a free 30-day trial of Airbrake. Quick sign-up, no credit card required. Get started.

Источник

Unsupported Operation Exception Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Thrown to indicate that the requested operation is not supported.

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

Constructs an UnsupportedOperationException with no detail message.

A constructor used when creating managed representations of JNI objects; called by the runtime.

Constructs an UnsupportedOperationException with no detail message.

Constructs an UnsupportedOperationException with no detail message.

Constructs an UnsupportedOperationException with no detail message.

Fields

Properties

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

(Inherited from Throwable)Class(Inherited from Throwable)Handle

The handle to the underlying Android instance.

(Inherited from Throwable)JniIdentityHashCode(Inherited from Throwable)JniPeerMembersLocalizedMessage

Creates a localized description of this throwable.

Returns the detail message string of this throwable.

(Inherited from Throwable)PeerReference(Inherited from Throwable)StackTrace(Inherited from Throwable)ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

(Inherited from Throwable)Dispose()(Inherited from Throwable)Dispose(Boolean)(Inherited from Throwable)FillInStackTrace()

Fills in the execution stack trace.

Initializes the cause of this throwable to the specified value.

Prints this throwable and its backtrace to the standard error stream.

Prints this throwable and its backtrace to the standard error stream.

Prints this throwable and its backtrace to the standard error stream.

Sets the Handle property.

Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.

(Inherited from Throwable)ToString()(Inherited from Throwable)UnregisterFromRuntime()(Inherited from Throwable)

Explicit Interface Implementations

IJavaPeerable.Disposed()(Inherited from Throwable)
IJavaPeerable.DisposeUnlessReferenced()(Inherited from Throwable)
IJavaPeerable.Finalized()(Inherited from Throwable)
IJavaPeerable.JniManagedPeerState(Inherited from Throwable)
IJavaPeerable.SetJniIdentityHashCode(Int32)(Inherited from Throwable)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates)(Inherited from Throwable)
IJavaPeerable.SetPeerReference(JniObjectReference)(Inherited from Throwable)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *