Writing your own exception

If the Java standard library doesn't contain an exception that fits with the business requirements of your application, you can implement your own exception. All exceptions that inherit the Error class must be thrown by the Java Virtual Machine, so we shouldn't extend this class. If you decide to implement your own exception, you should prefer to create only checked exceptions because, if you throw an exception with the RuntimeException type, there is no guarantee that it will be caught in Java code. In Kotlin, you can extend any subtype of the Exception class because Kotlin doesn't support a checked exception.

Let's suggest that we want to develop a ToDo list application that contains the ToDoStorage class, which contains the set method and throws ToDoAlreadyExistException. The ToDoStorage class may look as follows:

class ToDoStorage {
private val todos = HashMap<String, ToDo>()

operator fun get(name: String) = todos[name]

operator fun set(name: String, todo: ToDo) {
if (todos.contains(name)) {
throw ToDoAlreadyExistException()
}
todos[name] = todo
}
}

This contains the todos property that stores an instance of the ToDo class:

class ToDo(val name: String, val content: String)

The ToDoStorage class also contains the get and set operator methods to access values from the todos property. If we try to set a ToDo with a name that is already used as a key by the todos property, the ToDoAlreadyExistException will be thrown:

class ToDoAlreadyExistException(
message: String? = null,
cause: Throwable? = null,
enableSuppression: Boolean = true,
writableStackTrace: Boolean = true
) : Exception(message, cause, enableSuppression, writableStackTrace)

We can check this by using the following code:

fun main(args: Array<String>) {
val storage = ToDoStorage()
val todo = ToDo("name", "content")
storage[todo.name] = todo
storage[todo.name] = todo
}

The output looks like this:

Exception in thread "main" Chapter10.ToDoAlreadyExistException
at Chapter10.ToDoStorage.set(Example7.kt:20)
at Chapter10.Example7Kt.main(Example7.kt:30)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.35.122