0

I have two functions that invoke a code block with a try-catch like:

fun <R: Any> executeRestCall( block: () -> R ): R { try { return block() } catch (ex: RestClientException) { throw IllegalArgumentException(ex.message) } } fun <R: Any> executeProcessCall( block: () -> R ): R { try { return block() } catch (ex: RuntimeException) { throw IllegalStateException(ex.message) } } 

I need to parametrize required exception. How can this function be refactored?

14
  • 1
    What is the benefit of these methods? All you end up doing is erasing the stack trace Commented Sep 27, 2021 at 15:09
  • 1
    Even ignoring the drawback about hiding the stacktrace, what exactly would be the benefit of extracting anything here? It looks like the resulting function would just be reinventing the try-catch block Commented Sep 27, 2021 at 15:10
  • 1
    Does this answer your question? How to catch many exceptions at the same time in Kotlin Commented Sep 27, 2021 at 15:19
  • 1
    Does this answer your question then? Commented Sep 27, 2021 at 15:26
  • 2
    Just call block() without ever using these methods, then delete these methods :D Commented Sep 27, 2021 at 15:53

1 Answer 1

0

I'm not sure what you mean by parametrize

However, if you're looking for a way to indicate what exception the function will throw similar to the way throws works in Java - you can use @Throws annotation in kotlin

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-throws/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.