Ellen Spertus
11/07/2022, 4:04 PMclass WordleGame(val secretWord: String) {
companion object {
private val words = java.io.File("words.txt").readLines()
fun playGame() {
val game = WordleGame(words.random())
...
}
}
}
fun main() {
WordleGame.playGame() // ExceptionInInitializerError
}
Is there a clean way to catch a FileNotFoundException
? I can catch a ExceptionInInitializerError
in main()
and pull out its cause, but I'm hoping for something easier to explain to students, possibly restructuring the code.Chris Lee
11/07/2022, 4:05 PMEllen Spertus
11/07/2022, 4:12 PMplayGame()
is called.Chris Lee
11/07/2022, 4:14 PMephemient
11/07/2022, 4:22 PMlazy
then it will be loaded in the stackframe of the usage and an error will be thrown without being wrappedephemient
11/07/2022, 4:22 PMEllen Spertus
11/07/2022, 4:50 PMEllen Spertus
11/07/2022, 4:51 PMperformance-wise it would be negligible to read a text fileIn my other thread, I'm being told that concatenating a string message is so expensive it should be done lazily. 😅 https://kotlinlang.slack.com/archives/C0B8MA7FA/p1667832150499759
Chris Lee
11/07/2022, 4:53 PMChris Lee
11/07/2022, 4:54 PMlazy
will work for that - but that’s getting into complexities beyond what it appears you are teaching.Ellen Spertus
11/07/2022, 4:55 PMTies
11/07/2022, 6:21 PMYoussef Shoaib [MOD]
11/07/2022, 10:58 PMcompanion object {
private val words = try {
java.io.File("words.txt").readLines()
} catch (e: FileNotFoundException) {
// Provide default value
listOf("foo", "bar", "baz")
}
gildor
11/08/2022, 5:26 AM