Help with exception handling with getValue()

I need to get the value of the Map, and handle exceptions, but I can’t find any examples, would someone be so kind?

   data class Product(val details:String?,val price:Double)
        val producTable = mutableMapOf<Int,Product>()
            producTable.put(1,Product( "Mouse Usb xxxx",3.25))
            producTable.put(2,Product( "Keyboard Usb xxxx",4.25))
            producTable.put(3,Product( "Pendrive 16gb  xxxx",2.25))

            val nid:Int=0
            val result=producTable.getValue(nid)
            println(result.details)

Exception in thread "main" java.util.NoSuchElementException: Key 0 is missing in the map.
1 Like

Just use get or even [] instead. It returns null if the key isn’t there.

1 Like

As @kyay10 said, you can use get or [], and then deal with null values (see Null safety | Kotlin Documentation).

Here is one possibility:

data class Product(val details:String?, val price:Double)

val productTable = mutableMapOf<Int,Product>()
productTable[1] = Product( "Mouse Usb xxxx", 3.25)
productTable[2] = Product( "Keyboard Usb xxxx", 4.25)
productTable[3] = Product( "Pendrive 16gb  xxxx", 2.25)

val nid:Int = 0
val result = producTable[nid]
println(result?.details ?: "Product not found")

Alternatively, you can check the map first with containsKey. Generally, just have a look what operations work on maps, you can write much nicer code than in Java: Map-specific operations | Kotlin Documentation

2 Likes

Thanks guys, it works perfectly, I’m learning

@vmercadolibretuc as an alternative, you can also use withDefault to create a map that’ll return some default value from getValue (but not from [] or get) for keys not present in the map.

1 Like

Though this solves the problem but it can lead to another problem like NPE when you try something on return value. So maybe using withDefault is better wdyt ?

1 Like

This is depends on specific business logic you need.
NPE is not a problem in Kotlin as the type of the result value is Product? and compiler won’t let you forget to handle null case. Beauty of the strong typing with nullable classes

1 Like