Open In App

How to Throw a Custom Exception in Kotlin?

Last Updated : 25 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In addition to the built-in Exception Classes, you can create your own type of Exception that reflects your own cause of the exception. And you will appreciate the use of Custom Exception when you have multiple catch blocks for your try expression and can differentiate the custom exception from regular ones. Sometimes, there are cases where you want to create your own exception. If you are creating your own exception, it’s known as a custom exception or user-defined exception. These are used to customize the exception according to a specific need, and using this, you can have your own exception and a message. In this article, we will see how to create and throw a custom exception in Kotlin.

Example

Kotlin provides many built-in Exception Classes like IOException, ClassNotFoundException, ArithmeticException, etc. These are thrown at runtime by JVM when it encounters something it could not handle.

  • All the exceptions have Exception as their superclass, so we need to extend that class.
  • Here’s what our custom exception looks like:
class CustomException (message: String) : Exception(message)
  • Since the Exception superclass has a constructor that can take in a message, we’ve passed it with the help of the constructor of CustomException.

Now, if you have to throw an Exception, you will need to simply do the following:

throw CustomException ("threw custom exception")

The output will be something like this:

Let’s take a look at the implementation of the Exception class:

Kotlin




public class Exception extends Throwable {
  static final long serialVersionUID = -33875169931242299481;
public Exception () {
  }
public Exception (String var1) {
   super (var1);
}.....


 
 

As you can see, 

 

  • We have a second constructor that takes a String as a parameter. In our CustomException class, we have supplied it by passing its message to the superclass’s constructor.
  • Also, you can create a custom exception with an empty constructor because the exception also has an empty constructor.

Note: If you are using the IntelliJ IDE, just a simple copy/paste of Java code can convert it to Kotlin.

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads