Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a val inside a Kotlin catch block

I have the following code:

val targetImage: TargetImage?

try
{
  targetImage = someFunctionThatCanThrowISE()
}
catch (e: IllegalStateException)
{
  targetImage = null
}

The compiler says "val cannot be reassigned" and I can see that it could possibly be that some other line of code (not shown in this example) could throw ISE after targetImage has been set inside the try block.

What is the best practice to handle setting a val to some value (be it null or some other value) in a try-catch in Kotlin? In the present case if I remove the set in the catch it will leave targetImage unset and there isn't a way to test for an unset value as far as I can see, so I can't use targetImage after this block. I could change the val to a var but I don't want targetImage to be reassigned.

like image 339
cbn Avatar asked Mar 03 '18 17:03

cbn


People also ask

Can we call a method inside catch block?

It it keeps on throwing exceptions, then it may result in an infinite loop causing java heap space error. You should call a method that handles that exception or takes some appropriate steps for exception. Now for your question, you can call any method that is accessible inside your method A() inside the catch block.

How do you catch error in Kotlin?

In Kotlin, we use try-catch block for exception handling in the program. The try block encloses the code which is responsible for throwing an exception and the catch block is used for handling the exception. This block must be written within the main or other methods.


1 Answers

The try block in Kotlin is an expression, so you could just set the value of the try/catch to targetImage...

val targetImage: TargetImage? = try {
    someFunctionThatCanThrowISE()
} catch (e: IllegalStateException) {
    null
}

Or if you don't want that try/catch in the middle of your field declarations, you could call a function.

val targetImage: TargetImage? = calculateTargetImage()

private fun calculateTargetImage(): TargetImage? = try {
    someFunctionThatCanThrowISE()
} catch (e: IllegalStateException) {
    null
}
like image 64
Todd Avatar answered Oct 07 '22 23:10

Todd