I have one method throwing MyOwnException, but we all know that it is suggested to wrap it with RunTimeException when we are calling within streams. So here is the implementation I have done:
package com.company;
import java.util.Arrays;
import java.util.List;
public class Main {
static class MyOwnException extends Exception {
}
public static void main(String[] args) throws MyOwnException {
// write your code here
List<String> input = Arrays.asList("bad", "ok");
try {
long i = input.parallelStream().map(s -> tryIfBadStringThrowExceptionIdentity(s)).count();
}
catch (RuntimeException re) {
String s = re.getMessage();
if(s.equalsIgnoreCase("MyOwnException"))
throw new MyOwnException();
}
}
private static String ifBadStringThrowExceptionIdentity(String s) throws MyOwnException {
if(s.equalsIgnoreCase("bad"))
throw new MyOwnException();
else return s;
}
private static String tryIfBadStringThrowExceptionIdentity(String s) {
try {
return ifBadStringThrowExceptionIdentity(s);
} catch (MyOwnException e) {
throw new RuntimeException("MyOwnException");
}
}
}
Passing string and then again creating exception back via the string, is it best practices, or you have some elegant solution to this? if this is best way, am I the only one started disliking Java? And by the way, why only RunTimeException is valid for Streams related exception, does it impact code speed converting string back to exception?