Exception handling

We have already seen how the dao layer throws the exception, and how the controller layer handles that exception and returns a proper error message to the requesting client.
Let's quickly see the details of the exception-handling code.

We can create our own exception class, which we can use in our business cases as appropriate.

To create an exception class, we need to extend either the Exception or Throwable class, shown as follows:

class IdentityNotFoundException(message: String) : Exception(message) {

}

Alternatively, we can use the following code:

class IdentityNotFoundException(message: String) : Throwable(message) {

}

As shown in the preceding code, the custom exception class has to be inherited from either the Throwable or Exception class, and invoke its parent class constructor. To invoke the parent class constructor in Java, we can use the super or this keyword. In Kotlin, these keywords do not exist.

An exception type can be created without a constructor or an error message, as follows:

class IdentityException() :Throwable() {

}

An exception can be thrown using the throw keyword and an error message:

 throw IdentityNotFoundException("Requested Identity not found")

The code can handle the exception using the try...catch block:

  try {
//…
} catch (e: IdentityNotFoundException) {
//…
}

We can also provide the finally block for closing the resource of any that we have opened in the try block, as follows:

  try {
//…
} catch (e: IdentityNotFoundException) {
//…
}finally {
//…
}
..................Content has been hidden....................

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