Quinten Stekelenburg
Quinten Stekelenburg

Reputation: 21

Can someone explain why this fix for a NullPointerException works?

My application parses .xml files and transforms them into Kotlin classes. It builds JavaClasses based on XSD files. One of the NonNull properties was null, which was causing an uncaught exception. So I decided to wrap it in a try..catch in order for us to catch it and print additional information. However, I got a NullPointerException on the line where the function was invoked.

Implementation 1 (NPE on function invocation, not caught):

private fun Message.statusInformation(body: StatusBody) = try {
            this.statusInformation //Function marked as @NotNull in generated Javacode
        } catch (e: NullPointerException) {
            //Logging and throwing a different exception
        }

Implementation 2 (NPE was caught in the handler):

private fun Message.statusInformation(body: StatusBody): StatusInformation = try {
            this.statusInformation //Function marked as @NotNull in generated Javacode
        } catch (e: NullPointerException) {
            //Logging and throwing a different exception
        }

From the callers perspective the type was still StatusInformation, but the second implementation worked like expected.

Can someone explain why adding the return type to the expression prevented the uncatchable NPE? Or where to find documentation on this, I was unable to find any.

Upvotes: 2

Views: 75

Answers (1)

Hugo Cortez
Hugo Cortez

Reputation: 11

In implementation 1 you don't say the return type explicitly, so Kotlin tries to infer the return type, but this method is like NotNull, so if it returns null, the NullPointerException error occurs before the try -catch and therefore the error was not caught.

In implementation 2 you declare the return type, then Kotlin handles everything within try-catch, which is why it can detect NullPointerException in the catch block

Upvotes: 0

Related Questions