Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

240
Vistas
Throw exception in optional in Java8

There is a method get(sql) (I can not modify it). This method returns MyObjects and it has to be in try catch block because JqlParseException is possible there. My code is:

String sql = something;
try{
   MyObject object = get(sql);
} catch(JqlParseException e){
   e.printStackTrace();
} catch(RuntimeException e){
   e.printStackTrace();
}

I want to remove try catch and use Optional class, I tried:

MyObject object = Optional.ofNullable(get(sql)).orElseThrow(RuntimeException::new);

but IDE force there try catch too. And for:

MyObject object = Optional.ofNullable(get(sql)).orElseThrow(JqlParseException::new));

is an error (in IDE) The type JqlParseException does not define JqlParseException() that is applicable. Is there any way to avoid try catch blocks and use optional?

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Optional is not intended for the purpose of dealing with exceptions, it was intended to deal with potential nulls without breaking the flow of your program. For example:

 myOptional.map(Integer::parseInt).orElseThrow(() -> new RuntimeException("No data!");

This will automatically skip the map step if the optional was empty and go right to the throw step -- a nice unbroken program flow.

When you write:

 myOptionalValue.orElseThrow(() -> new RuntimeException("Unavailable"));

... what you are really saying is: Return my optional value, but throw an exception if it is not available.

What you seem to want is a way to create an optional (that instantly catches the exception) and will rethrow that exception when you try using the optional.

about 4 years ago · Santiago Trujillo Denunciar

0

That's not how Optionals work. They don't make try-catch-blocks obsolete. However, you could introduce a new wrapper-function like this:

public Optional<MyObject> getMyObject(final String jql) {
    try {
        return Optional.ofNullable(get(sql));
    } catch (final JqlParseException e) {
        return Optional.empty();
    }
}

You won't have to deal with the exception anymore, but you won't know if there was an error if you get an empty Optional as well.

about 4 years ago · Santiago Trujillo Denunciar

0

Try this

Optional.ofNullable(result)
                .orElseThrow(() -> new GenericClientException("Request body is not valid", HttpStatus.BAD_REQUEST));
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda