Left Index

Kotlin Throws Exception

Exceptions are thrown by JRE(Java Runtime Environment) at runtime. In addition to JRE, user can throw it explicitly for their own cause. User can throw inbuilt Exceptions like ArithmeticException, Exception, etc., or a custom built Exception.


To throw an exception to the calling method, use throw keyword.

Syntax:
throw Exception(message : String)
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()}")
	}
}

fun validNum(num: Int): Int {
	if(num < 10) {
		throw Exception("Not a valid number")
	}
	
	return num
}
Output:
Error: java.lang.Exception: Not a valid number