is it OK to have a constructor throw an exception ...
# getting-started
is it OK to have a constructor throw an exception or is it bad practice ?
What do you mean by that? Do you mean throwing an exception from the constructor of the class?
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
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
can throw if the expression is invalid AFAIK
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
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.
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
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).
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.