Reputation: 65
This is a simple scala code for checking prime number. When I compile at command prompt, I get the following warning. I thought I would care less for warning. But it didn't create the .class files. Can someone share what this warning means?
warning: This catches all Throwables. If this is really intended, use case _ : Throwable
to clear this warning.
object PrimeNumber extends App {
println("11 is prime number : " + checkPrimeNumber(11))
println("111 is prime number : " + checkPrimeNumber(111))
//Method for checking prime numbers between 1 and 100
def checkPrimeNumber(num: Int) = {
try {
if (num < 1 || num > 100)
throw new IllegalArgumentException("Number should be between 1 and 100")
else
isPrimeNumber(num)
} catch {
case e: IllegalArgumentException => e.printStackTrace()
case _ => println("Exception has occurred!")
}
}
//Non Functional Method for finding prime number
def isPrimeNumber(number: Int): Boolean = {
var i = 2
while (i <= number / 2) {
if (number % i == 0) {
return false
}
i += 1
}
true
}
}
Upvotes: 1
Views: 947
Reputation: 4161
It is dangerous to catch Throwable
in Java, and even more in Scala.
Instead, use this:
catch { case scala.util.control.NonFatal(e) => // do something }
See http://www.tzavellas.com/techblog/2010/09/20/catching-throwable-in-scala/
Upvotes: 5