Scala

Scala

Made by DeepSource

Explicit trap of NullPointerException SC-W1021

Bug risk
Major

Explicit trapping of NullPointerException is considered a bad practice in both Scala and Java. It usually means that your application has come across a null reference in an unexpected manner which you're trying to suppress by explicitly trapping through a catch block rather than finding the root cause. Since this was unexpected, it is probably not safe for your application to continue with the execution.

Another idea is to rely on Option[T] instead of null. Have your methods return Some(_) if the call succeeds and None if the call fails, an approach taken by many of Scala's built-in methods. If you truly have to rely on null, use if-else to explicitly check for null references rather than relying on try-catch.

Bad practice

val result = fetchData(...)
try {
  processResult(result)
} catch {
  case e: NullPointerException => ...
}

Recommended

fetchData(...) match {
  case Some(result) => processResult(result)
  case None => ...
}