- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Why does scala.App swallow exceptions during construction ?
Tue, 2011-05-17, 15:31
If I have this singleton :
object Test extends App {
def z = "1"
sys.error("!!!!")
}
launch the REPL console, and do :
scala>Test.z
res0: java.lang.String = 1
The exception is silenced,
If I don't extend App, it doesn't.
Is there a good reason for this ?
Thanks
Tue, 2011-05-17, 19:37
#2
Re: Why does scala.App swallow exceptions during construction ?
The behavior you are observing is what the App trait was meant to produce.
2011/5/17 Maxime Lévesque :
>
> If I have this singleton :
>
> object Test extends App {
> def z = "1"
> sys.error("!!!!")
> }
>
> launch the REPL console, and do :
>
> scala>Test.z
> res0: java.lang.String = 1
>
> The exception is silenced,
> If I don't extend App, it doesn't.
>
> Is there a good reason for this ?
>
> Thanks
>
Wed, 2011-05-18, 09:47
#3
Re: Why does scala.App swallow exceptions during construction ?
On 17/05/2011 18:44, Paul Phillips wrote:
> This has an interesting implication that I hadn't really noticed before, which is that the whole object "constructor" will be executed every time main is run.
>
> scala> object Test extends App { println("Bippy!") }
> defined module Test
>
> scala> Test main null
> Bippy!
>
> scala> Test main null
> Bippy!
>
> scala> Test main null
> Bippy!
Interesting. So now, we have what looks like a constructor, but behave
differently. I believe that will open a new world of wonder and
amazement, especially regarding side effects. Or heavy processing and
long action, what I think were one of the reason to create a delayedInit
out of the constructor.
We are living interesting times :)
On 5/17/11 7:31 AM, Maxime Lévesque wrote:
> object Test extends App {
> def z = "1"
> sys.error("!!!!")
> }
>
> launch the REPL console, and do :
>
> scala>Test.z
> res0: java.lang.String = 1
>
> The exception is silenced,
No, it isn't thrown.
> Is there a good reason for this ?
There is, at least, a reason. The point of delayedInit is to delay init. The contents of the App constructor (which is only the call to sys.error) are not run until main is.
scala> Test main null
java.lang.RuntimeException: !!!!
at scala.sys.package$.error(package.scala:27)
at Test$delayedInit$body.apply(:23)
at scala.Function0$class.apply$mcV$sp(Function0.scala:34)
This has an interesting implication that I hadn't really noticed before, which is that the whole object "constructor" will be executed every time main is run.
scala> object Test extends App { println("Bippy!") }
defined module Test
scala> Test main null
Bippy!
scala> Test main null
Bippy!
scala> Test main null
Bippy!