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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With