Reputation: 31
I've just started learning Scala, so this might be a simple question. I want to use a try-catch block to check if a variable has been declared or not.
I am using a try-catch block and catching the NoSuchElementException
if the variable doesn't exist.
try{
print(testVariable)
}
catch{
case e: NoSuchElementException => print("testVariable not found")
}
My code is showing an error that testVariable
does not exist instead of throwing the exception. I then tried multiple other exceptions as well, but Scala's try-catch doesn't seem to be catching any of them (except for the divide by zero exception).
Can someone please guide me on how to use Scala's try-catch block?
Upvotes: 0
Views: 707
Reputation: 13922
In Scala (or pretty much any compiled programming language really), checking if a variable has been declared or not is the compiler's job, done at compile time. If you try to use a variable that hasn't been declared, the compiler will give an error, and your code won't be able to run.
Exceptions are a way to represent problems at run-time.
There is no overlap between "compile time" and "run-time", so what you are trying to do doesn't make sense. There just isn't an exception for "variable does not exist", and that's why you can't catch it.
To contrast, take this example:
val map = Map('a' -> 1, 'b' -> 2)
map('c') // will throw NoSuchElementException because there is no 'c' in the map
In this case, map.apply('c')
(syntax sugar for apply
lets you do map('c')
will throw an exception because that's how Map's apply method is implemented. See the definition of Map#apply
which calls Map#default if the key wasn't in the map; Map#default
throws a NoSuchElementException.
You could catch that exception with a try/catch, e.g.
try {
map('c')
} catch {
case e: NoSuchElementException =>
println("got it!")
}
Upvotes: 8