Android Studio Requires Catching Throwable when using orElseThrow method
Android Studio Requires Catching Throwable when using orElseThrow method
I am writing an application in Android Studio. My current version is 3.1.0. I am trying to use the orElseThrow method from the Optional class. I checked the settings for Android Studio, and it requires an API level of at least 24 to use Optional. I'm currently using API level 25, and my JDK is 1.8.0_151.
I have created a new Android Studio project using an Empty Activity. I have created a class called TestClass that contains the following code:
package com.examples.myapplication;
import java.util.Arrays;
import java.util.List;
public final class TestClass {
private final List<Integer> numbers;
public TestClass() {
numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
}
public final int doesNumberExist(final int number) {
return numbers.stream().filter(n -> n == number).findAny().orElseThrow(RuntimeException::new);
}
}
The problem that I'm having here is that Android Studio gives me a compile-time error on the orElseThrow() call in the doesNumberExist() method.
The error is:
Unhandled exception: java.lang.Throwable
I've tried running the orElseThrow method in a different IDE, and there is no compile-time error on that line of code, so I believe that the problem lies in Android Studio, but I can't figure out what would be causing the problem. I have tried raising the API level, but I can only go up to 26, and that didn't do anything.
From my understanding of the way that the orElseThrow() method works, the type of exception that you should have to handle is any checked exception that you throw inside the method call. In this example, I've used RuntimeException, so I shouldn't have to handle catching any exceptions.
Great suggestion @Radiodef & a tip:
[mcve] in a comment auto-expands to Minimal, Complete, and Verifiable example.– Andrew Thompson
Jul 1 at 1:19
[mcve]
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
It would be helpful if you could update your question with a minimal, complete example so we can reproduce the problem.
– Radiodef
Jul 1 at 0:32