What is IndexOutOfBounds?
IndexOutOfBoundsException is a subclass of RuntimeException mean it is an unchecked exception which is thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.
How handle this?
Let's suppose we have an array with prices and we need to get a value in a specified position, like that
(def prices [100 200 300])
(println (prices 0)) ;returns 100
(println (prices 100)) ;IndexOutOfBoundsException
We can get this using the array as a "function" but what if we don't have a position we want to pursue? This will crack our flow...
Your program will pop an Exception and not proceed, we need to persist the flow so...
Clojure is amazing and give to us a core method symbol get
According the docs its returns the value mapped to key, not-found or nil if key not present, besides that we can define a default value.
Handling this like a charm
(def prices [100 200 300])
(println (get prices 0)) ;returns 100 normally
(println (get prices 100))
;returns nil, because our array only have 3 positions, and 100 is a value of that
;We can define a default value when a position doesn't exist
(println (get prices 100 0))
That's it for now 🍻
Therefore, now you can handle your array and without worrying about an exception popping and stopping your normally working program
See more about Clojure if you want here.
Top comments (0)