Left Index

Kotlin Custom Exception

In addition to the built-in Exception Classes, you can create your own type of Exception that reflects your own cause of 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.


The create custom Exception class should extend Exception class. Following is the syntax of Custom Exception in Kotlin

Exception has following three properties
  • Message: show error message
  • Stack Trace: complete stack trace from where exception generated
  • Cause (Optional)
Syntax:
class ExceptionName(msg: String): Exception(msg)

Example:
package com.theitbulls.kotlinex

import java.lang.ArithmeticException

fun main(args: Array<String>) {
	try {
		var num = validNum(9)
		println("Valid number: ${num}")
	} catch (e: Exception) {
		println("Error: ${e.toString()}")
	}
}

// create custom exception i.e. InvalidNum
class InvalidNum(msg: String) : Exception(msg)

fun validNum(num: Int): Int {
	if(num < 10) {
		throw InvalidNum("Not a valid number")
	}
	
	return num
}
Output:
Error: com.theitbulls.kotlinex.InvalidNum: Not a valid number