I have this code in Scala, a
object should be value not a variable, How can I initialize the a
object in the try block?
object SomeObject {
private val a : SomeClass
try {
a=someThing // this statement may throw an exception
}
catch {
case ex: Exception=> {
ex.printStackTrace()
}
}
}
The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.
catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control flow exits the entire construct.
The try/catch construct is different in Scala than in Java, try/catch in Scala is an expression. The exception in Scala and that results in a value can be pattern matched in the catch block instead of providing a separate catch clause for each different exception. Because try/catch in Scala is an expression.
Scala tries to avoid undefined/null values. However, you can solve the problem by giving return values for the cases if the try
fails and initializing a
with the whole try
expression:
private val a: SomeClass =
try {
someThing // this statement may throw an exception
} catch {
case ex: Exception => {
ex.printStackTrace()
someDefault
}
}
Update: In Scala it would be probably more idiomatic to use Try
from scala.util
:
val x : Int =
Try({
someThing
}).recoverWith({
// Just log the exception and keep it as a failure.
case (ex: Throwable) => ex.printStackTrace; Failure(ex);
}).getOrElse(1);
Try
allows you to compose computations that can fail with an exception in various ways. For example, if you have two computations of type Try
you can call
thing1.orElse(thing2).getOrElse(someDefault)
This runs thing1
and returns its result, if it's successful. If it fails, it continues with thing2
. If it fails too, returns someDefault
. You can also use recover
or recoverWith
to recover from some exceptions using partial functions (and potentially reuse those partial functions).
Since in Scala blocks have return values, and the last expression is the return value per default, you can do this:
object SomeObject {
private val a : SomeClass = { //this additional block not necessary, but added for clarity
try {
someThing // this statement may throw an exception
}
catch {
case ex: Exception=> {
ex.printStackTrace()
null
}
}
}
}
. However, I have to add that this looks like you're trying to accomplish something potentially blowing up in your face later - you will need null
checks in any code that uses the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With