All posts

Fix Null Reference in Clojure

Handle NullPointerException in Clojure code, covering nil punning, Java interop null safety, and defensive programming patterns.

NullPointerException in Clojure

Clojure's nil is Java's null. While Clojure handles nil gracefully in many cases (nil punning), Java interop and certain operations still throw NullPointerException.

Where Nil Is Safe

Clojure's core functions handle nil gracefully:

(count nil)        ; => 0
(first nil)        ; => nil
(str nil)          ; => ""
(conj nil :a)      ; => (:a)
(get nil :key)     ; => nil
(seq nil)          ; => nil

Where Nil Throws

;; Java interop — NPE
(.toUpperCase nil)  ; NullPointerException

;; Arithmetic
(+ 1 nil)           ; NullPointerException

;; Keyword as function on nil is safe, but...
(:key nil)          ; => nil (safe)
(nil :key)          ; NullPointerException (nil is not a function)

Defensive Patterns

Use some-> and some->> for nil-safe threading:

;; Without — throws if any step returns nil
(-> user :address :city .toUpperCase)

;; With some-> — short-circuits on nil
(some-> user :address :city .toUpperCase)
; Returns nil instead of throwing

Java Interop Safety

;; Guard against nil from Java methods
(when-let [result (.getData java-obj)]
  (process result))

;; Or use fnil for nil-safe functions
(def safe-inc (fnil inc 0))
(safe-inc nil)  ; => 1

Spec Validation

(require '[clojure.spec.alpha :as s])

(s/def ::name string?)
(s/def ::user (s/keys :req-un [::name]))

;; Validate before processing
(when (s/valid? ::user data)
  (process data))

Bugsly captures NullPointerException in Clojure applications with the full stack trace and the expression that triggered it, making it straightforward to find where nil unexpectedly appeared.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free