Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to handle invalid argument in Scala

4 Answers

0 votes
def checkNumber(num: Int): Unit = {
  if (num < 0) throw new IllegalArgumentException("Negative numbers are not allowed")
  println(s"number: $num")
}

try {
  checkNumber(-8) // Throws IllegalArgumentException
} catch {
  case e: IllegalArgumentException => println(s"Error: ${e.getMessage}")
}


 
/*
run:

Error: Negative numbers are not allowed

*/

 



answered May 21, 2025 by avibootz
0 votes
def isValidInput(num: Int): Boolean = num >= 0

val num = -8
if (isValidInput(num)) println(s"Valid input: $num")
else println("Invalid input detected - Number must be positive")



 
/*
run:

Invalid input detected - Number must be positive

*/

 



answered May 21, 2025 by avibootz
0 votes
def safeProcessNumber(num: Int): Option[Int] =
  if (num < 0) None else Some(num * 2)

safeProcessNumber(-1) match {
  case Some(value) => println(s"Result: $value")
  case None        => println("Invalid argument detected - Number must be positive")
}


 
/*
run:

Invalid argument detected - Number must be positive

*/

 



answered May 21, 2025 by avibootz
0 votes
def safeDivide(a: Int, b: Int): Either[String, Int] =
  if (b == 0) Left("Division by zero is not allowed") else Right(a / b)

safeDivide(4, 0) match {
  case Right(result) => println(s"Result: $result")
  case Left(error)   => println(s"Error: $error")
}


 
/*
run:

Error: Division by zero is not allowed

*/

 



answered May 21, 2025 by avibootz

Related questions

4 answers 374 views
4 answers 394 views
4 answers 336 views
3 answers 279 views
3 answers 281 views
6 answers 521 views
...