Kotlin NullPointerException Tutorial

In this section, we will learn what the NullPointerException is and how to handle such exception in Kotlin.

What is NullPointerException in Kotlin?

In Kotlin, if you try to call a variable with null value and invoke a function or property on it (intentionally or unintentionally), you’ll get an exception of type NullPointerException.

This essentially means you’re trying to call a variable that has a null value! And so because a null value doesn’t have any function or property, invoking anything on it would cause you this exception.

Controlling NullPointerException in Kotlin: Using Safe Call Operator

Now there are multiple ways by which we can control and stop the NullPointerException exception from occurring! One of them is the safe call operator.

We’ve explained this operator in previous sections, but in short, using this operator, we can first check the value of a variable to see if it’s null or not. If it was, then the operation will stop immediately and the value null will return as the final result. But if the variable had a non-null value in it, the operation will proceed.

Example: using safe call operator in Kotlin

fun main(){
    var str:String? = null 
    val h = str?.uppercase() 
    println("The uppercase version of the string value is: $h")


The uppercase version of the string value is: null

Here we’ve checked the value of the str variable using the safe call operator to see if it’s null or not. Now, because this variable contains a null value, the operator terminates the operation (no call to the uppercase() function occurred) and the value null returns as a result.

Handling NullPointerException in Kotlin: Using try catch blocks

If you want to let the NullPointerException exception to happen but want to handle it afterward, you can use the try-catch blocks!

Simply set one of the catch clauses of a try block to NullPointerException and that will be invoked if an exception of this type was thrown in the body of the related try block.

Example: handling NullPointerExcepiton using try catch blocks in Kotlin

fun main(){
    var str:String? = null 
        if (str ==null){
            throw NullPointerException("The value of the str is null")
            println("This is the value of the str variable: $str")


The value of the str is null

Top Technologies