is it OK to have a constructor throw an exception ...
# getting-started
l
is it OK to have a constructor throw an exception or is it bad practice ?
j
What do you mean by that? Do you mean throwing an exception from the constructor of the class?
l
yes. sorry, i don’t know why i wrote “class” when i meant “constructor”
edited 🙂
Copy code
class Configuration @Throws(NoSuchFileException::class) constructor(val configFile: String = "config.yml") {
    init {
        if(!File(configFile).exists()) {
            throw NoSuchFileException(File(configFile), null, "Config file not found")
        }
    }
}
i ended up writing this
j
I think most of the time people avoid throwing during the construction (being in initializers, init blocks, or secondary constructor bodies). But I'd say as long as it makes sense for the class, it's ok. For instance
Regex
can throw if the expression is invalid AFAIK
l
i’m making a class to read a configuration file. it’s pretty much the first stuff main do. there is no point in continuing execution if there is no configuration. so i guess it’s tolerable in this case ?
👌 1
a
In my experience, the only language where throwing in the constructor was was a very bad idea is C++ because of memory safety. I don't imagine it would be a big deal in Kotlin.
l
yeah i had C++ in mind indeed. thank you. (it’s pretty much impossible to throw an exception in constructor in modern C++ without tons of warning and various insult from analyzer :D)
👍 2
l
I would make the constructor private, then call it from newInstance companion method which may return the object or null (assuming what the exception is doesn’t matter, for most cases).
1
r
In the case of a data class you must do any validation in the constructor (an init block) as making the constructor private doesn't make the copy function private, so validation in a companion object will be bypassed.