what situation will throw exception "scala.util.control.BreakControl"? - scala

My code throw exception scala.util.control.BreakControl, but I don't know why. Does anyone know?
Some place I use breakable and break, but I don't why cause this exception.
fragment 1
breakable {
for (quaOfLine <- dataOfLine) {
try {
// ... some other code
if (judgeTime(jsonQua.getInt("startTime")) == judgeTime(jsonLine.getInt("startTime"))) {
// ... some other code
if (quaRRIDs.length / RRIDs.length.toFloat >= 0.8 || quaRRIDs.length / RRIDs.length.toFloat <= 1.2) {
var count = 0
breakable {
for (rrid <- RRIDs) {
for (quaRRID <- quaRRIDs) {
if (rrid == quaRRID) {
count += 1
break //break
}
}
}
}
if (count / RRIDs.length.toFloat >= 0.8) {
sameLine = qualifier + "::" + value
break // break
}
}
}
} catch {
case e: Throwable => e.printStackTrace
}
}
}
fragment 2
breakable {
for (quaOfDest <- dataOfDest) {
try {
val qualifier = quaOfDest.getString("qualifier")
val value = quaOfDest.getString("value")
val jsonQua = new JSONObject(value)
val (quaSLon, quaSLat, quaELon, quaELat) = getSELonLat(jsonQua)
if (jsonQua.getInt("timeBucket").toString == judgeTime(jsonLine.getInt("startTime"))) {
someDest = qualifier + "::" + value
break //break
}
} catch {
case e: Throwable => e.printStackTrace
}
}
}

scala.util.control.BreakControl is thrown by the method scala.util.control.Breaks.break. It is used for simulating the break statement from Java. It is used like this:
import scala.util.control.Breaks.{break, breakable}
breakable {
for(i <- 1 until 10) {
println(i)
if(i > 5) break
}
}
BreakControl is a private class so normally it won't be thrown by anything else than break.
This also means that inside a breakable block you shouldn't catch BreakControl yourself. You break inside a try block and then catch all Throwables and print them. BreakControl is a Throwable so it will be caught by you instead of by the breakable method.
If you really want to catch all Exceptions/Throwables, you should do something like this:
import scala.util.control.Breaks.{break, breakable}
import scala.util.control.ControlThrowable
breakable {
for(i <- 1 until 10) {
try {
println(i)
if(i > 5) break
} catch {
case c: ControlThrowable => throw c
case t: Throwable => t.printStackTrace
}
}
}
The Scala Standard Library also includes a special construct for cases like this which lets you catch all Throwables except for fatal ones like OutOfMemoryError or StackOverflowError, and also everything that extends ControlThrowable:
import scala.util.control.NonFatal
try {
//do stuff
} catch {
case NonFatal(e) => e.printStackTrace
}

Related

How can I Throw error inside scodec Attempt?

I have the following code to decode a BitVector. How can I remove the exception and throw a failure?
def decode(b: BitVector) = {
if (!applies) {
Attempt.successful(DecodeResult.apply(null, b))
} else {
string.decode(b) match {
case Attempt.Successful(str) => {
val contentSize = str.value.slice(0, 2)
val content = str.value.slice(2, contentSize.hex2int() + contentSize.length)
if(!content.forall(_.isLetterOrDigit)){
throw new IllegalArgumentException()
}
val remain = str.value.slice(contentSize.hex2int() + contentSize.length, str.value.length)
Attempt.successful(DecodeResult.apply(content, BitVector(remain.getBytes)))
}
case Attempt.Failure(e) => Attempt.failure(e)
}
}
}

Scala create a List with Future in a for loop and check the result of each Future

I need to process list of entry in parallel and validate the results. Can anybody help me in achieving this in Scala
it is something like below,
FileList = List { "/temp/File1", "/temp/File2","/temp/File3","/temp/File4"........}
for( file <- FileList){
Future { getRecCount(file) } // Need to create a List with all Futures
}
Now i need to check the result of all Futures till it completes
getRecCount - will calculate the record count and writes into an file
If you're just interested in Exception, you can wrap the body of Future in Try and use Future.traverse as #adrice727 mentioned for paralles files processing:
// Sequence of files for processing
val files = Seq[String]("/tmp/1.txt", "/tmp/2.txt", "/tmp/3.txt", "/tmp/4.txt",
"/tmp/5.txt", "/tmp/6.txt")
def fileHandler(path: String): String = {
val idx = files.indexOf(path)
// Throw exception for each second file
if (idx % 2 == 0) throw new Exception(s"Unable to hande $path")
else path
}
val futures: Future[Seq[Try[String]]] = Future.traverse(files){ path =>
Future {
// Wrap it by Try
Try {
// Each file handler
fileHandler(path)
}
}
}
futures.map { seq =>
seq.map {
case Success(s) => println(s"Result: $s")
case Failure(ex) => println(s"Exception: ${ex.getMessage}")
}
}
Thanks - This is how i implemented
val tobeProcesssed : Seq[String] = Seq("FileName1", "FileName2", "FileName3,"FileName4) // Created a Seq with File Names
val latch = new CDL(tobeProcesssed.size)
val trackFutures: Future[Seq[Try[Boolean]]] = Future.traverse(tobeProcesssed.seq) { fileNm =>
Future {
LOG.info("In the Futures Loop for {}", fileNm)
Try {
doProcessing(fileNm)
}
}
}
trackFutures.map { seq =>
seq.map {
case Success(state) => {
if (state) {
LOG.info("On Sucess - {} - {}", latch.getCount, state)
return = 0
latch.countDown()
} else {
LOG.error("Failed - {} - {}", latch.getCount, state)
while (latch.getCount > 0) {
return = 1
latch.countDown()
}
}
}
case Failure(exception) => {
LOG.error("Versioning Failed -{} - {}", latch.countDown(), exception)
while (latch.getCount > 0) {
return = = 1
latch.countDown()
}
}
}
}
latch.await()

Scala compilation warning and failure. Warning: This catches all Throwables

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
}
}
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/

Scala - Breaking out of a loop in a try-catch block

I have the following Scala code:
breakable {
someFile.foreach { anotherFile =>
anotherFile.foreach { file =>
try {
val booleanVal = getBoolean(file)
if (booleanVal) break //break out of the try/catch + both loops
} catch {
case e: Throwable => //do something
}
}
}
}
it's the if (booleanVal) break that doesn't work, because it seems like Scala makes it work as an exception. How do I break out of this nested loop?
Move if (booleanVal) break out of try block:
val booleanVal = try {
getBoolean(file)
} catch {
case e: Throwable => //do something
}
if (booleanVal) break // break out of the try/catch + both loops
I suggest you to not use break, for the first this is ugly :) and the second, this is unreadable.
Maybe you would like something like this:
for {
anotherFile <- someFile
file <- anotherFile
b <- Try(getBoolean(file))
if(b)
} /// do something
If you need to do more work in the try block, you can write:
for {
anotherFile <- someFile
file <- anotherFile
} Try{ if(!getBoolean(file)) /* */ } match {
case onSuccess(v) =>
case onFailure(e: Throwable) =>
}

Scala - how to make val visible

I have this method
def example(something):something {
val c=List()
if(){
if(){
val a=List()
}
else{
val a=List()
}
}
//here a or b are not declared
c:::a
}
How to declare it and make it visible? I can not use var.
You can't make it visible outside declaration scope, so, maybe, try this:
def example(somthing):somthing{
val c = {
if (something) {
(0 to 10).toList
} else {
(0 to 5).toList
}
}
}
Almost Everything in Scala returns a value (the exception is for statements such as package declarations and imports)
if/else statements, pattern matches, etc. etc.
This means that your if/else block returns a value, and is especially keen to do so, very much like the ?: ternary operator in Java.
val foo = ... some integer ...
val bar = if(foo >= 0) "positive" else "negative"
Or using blocks:
val foo = ... some integer ...
val bar = if(foo >= 0) {
"positive"
} else {
"negative"
}
Nest 'em to your heart's content if you wish!
val foo2 = ... some other integer ...
val bar = if(foo >= 0) {
if(foo2 >= 0) {
"double positive"
} else {
"part-way there"
}
} else {
"foo was negative"
}
and even mix 'n' match styles:
println(
if(foo >= 0) {
if(foo2 >= 0) "double positive" else "part-way there"
} else {
"foo was negative"
}
)
In your particular case, you do not need the val a:
def example(something):something {
val c= yourListC ::: if(firstTest){
if(secondTest){
yourListA
}
else{
yourOtherListA
}
} else {
anAdequateEmptyList
}
}