Johann
Johann

Reputation: 29885

Create an instance of Exception and modify its message

In Kotlin/Java, I would like to inherit from Exception but change the message when the Exception is instantiated. Something like this:

import java.lang.Exception

class TestAlreadyAddedException : Exception {
    constructor(details: String) {
       this.message = "Test already added: {details}" 
    }
}

But this is not allowed because Kotlin complains that message is a val that cannot be re-assigned. Is there a way around this?

Upvotes: 1

Views: 628

Answers (2)

Dak28
Dak28

Reputation: 259

You can simply do this:

Create simple exception class

class TestException(message:String): Exception(message)

Use it like this

throw TestException("Test already added: $message")

Upvotes: 0

Mahdi-Malv
Mahdi-Malv

Reputation: 19308

The Exception class takes it's message as a constructor parameter.

This should do it:

constructor(details: String): super(details) { 

}

Upvotes: 1

Related Questions