DEV Community

Cover image for Handling IndexOutOfBounds Exception in Clojure with Young Frankenstein GIFs
Marcos Henrique
Marcos Henrique

Posted on

3 2

Handling IndexOutOfBounds Exception in Clojure with Young Frankenstein GIFs

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
Enter fullscreen mode Exit fullscreen mode

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)) 

Enter fullscreen mode Exit fullscreen mode

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay