Updated February 21, 2023
Introduction to Kotlin Exceptions
The kotlin exceptions are one of the runtime problems which mainly used to occur on the programs which are not satisfied the conditions it may be of the default classes with methods, variables, and other keywords mainly, kotlin language used the unchecked type of exceptions that can be thrown at the runtime code execution with the help of throw keyword. So we can handle the custom exceptions which is required on the project, kotlin supports only unchecked exceptions. So it comes under all the exceptions it catches, and it is enforced by using the kotlin language compiler will check and execute the codes.
Syntax of Kotlin Exceptions
Kotlin language uses many default keywords, variables, and other built-in functions to implement mobile-based applications. Like that, exceptions are one of the features used in the language handled by the catch block.
fun main()
{
try
{
--some logic codes—
}
catch(e:Exception)
{
--some codes—
}
---some logic codes depend upon the requirement---
}
The above codes are the basic syntax for handling the exceptions using the try-catch blocks. We can also use the throw keyword to throw the custom exceptions, which are also handled in the catch blocks if required.
How does Exception work in Kotlin?
- Generally, the exception is the runtime issue handled by the compiler and occurs on the program. It may occur in any type like memory space, array index out of bound exceptions, and other conditions. Kotlin language accepts unchecked exceptions like Arithmetic, ArrayIndexOutOfBoundExceptions, Security Exception, and NullPointer Exception; these are unchecked exceptions handled by the kotlin language.
- The integer number is probably divided using the 0 number; the exception will be thrown and come under the Arithmetic exception. It has other different types of exceptions like IOException, etc. these exceptions are performed with each operation that can be considered and malformed on the kotlin language. If we want to create the custom exception, we can make our exceptions, which are validated and utilized with the specific keywords like throw, catch, and other blocks like finally, etc. Every block has its own valid checked and unchecked exceptions based on the project requirements.
- The exceptions indicate the problem or issues in the code to capture the indexes using tools like jtest for testing the principles. We can handle the exception using the exception handling mechanism regarding the runtime problems and program execution.
Examples of Kotlin Exceptions
Given below are the examples:
Example #1
Code:
package one
abstract class Planet(planetname:String){
abstract var name: String
abstract fun planetdetails()
init {
println("Planet name is: $name")
}
fun firstplanet(){
println("Thank you the Planet name is")
}
}
interface commonplanet {
var vars: String
fun earth():String
fun mars() {
println("Have a Nice day users")
}
}
class sun : commonplanet {
override var vars: String = "pluto"
override fun earth() = "jupiter"
}
class venus(planetname:String): Planet(planetname) {
override var name: String = "July"
override fun planetdetails() {
println("Thank you users your Planet is $name")
}
}
fun main() {
val m2 = venus("May")
println("Your current Planet is : ${m2.name}")
m2.planetdetails()
val j = sun()
println("Your latest Planet is = ${j.vars}")
print("Keep on spent the time with our application: ")
j.mars()
print("Nice day users ")
println(j.earth())
try{
println("Thank you users your planet details under exception")
throw Exception("Its having some issue please try later")
println("After getting all the details we got a exception")
}
catch(e: Exception){
println(e)
}
finally{
println("Kindly spent with time with our application and try it again")
}
}
Output:
In the above example, we used normal exceptions like java.lang.exception while throwing the customized user input datas if it’s not valid.
Example #2
Code:
package one;
class second {
companion object {
const val sample = "Welcomeusers"
}
fun demo() = sample;
var x = 0;
fun demo1(i: Int): Int {
return 6 * i
}
fun demo4(i: Int): Int {
return 6 * i + 1
}
fun demo4(y: Array<Int>, i: Int, j: Int) {
var z = y[i]
y[i] = y[j]
y[j] = z
}
fun demo4(y: Array<Int>, i: Int) {
var eg = demo1(i);
var eg1 = demo4(i);
var eg2: Int;
if ((eg <= x - 1) && (y[eg] > y[i])) {
eg2 = eg;
} else
eg2 = i
if ((eg1 <= x - 1) && (y[eg1] > y[eg])) {
eg2 = eg1
}
if (eg2 != i) {
demo4(y, i, eg2);
demo4(y, eg2);
}
}
fun demo1(y: Array<Int>) {
x = y.size
for (i in x / 2 downTo 0) {
demo4(y, i)
}
}
fun demo(y: Array<Int>) {
demo1(y)
for (i in y.size - 1 downTo 1) {
demo4(y, i, 0)
x = x - 1
demo4(y, 0)
}
}
}
fun main(arg: Array<String>) {
try{
println("Welcome To My Domain its the second example regarding kotlin exception")
println("Please enter your valuable inputs for to perform the sorting operations:")
var p = readLine()!!.toInt()
println("Enter your input datas so that sorting operation will be performed ")
var y = Array(p, { 0 })
for (i in 0 until p)
y[i] = readLine()!!.toInt()
var q = second();
q.demo(y)
println("Welcome To My Domain its y second sample for regarding the kotlin static concept")
for (i in 0 until p)
print("${y[i]} ")
}
catch(e:Exception)
{
println(e)
}
}
Output:
In the second example, we used additional operations like number format exceptions while entering string values instead of int numbers.
Example# 3
Code:
package one;
fun main(arg: Array<String>) {
var a= "Welcome Users its a third example regarding exception"
var b = try { a.toInt() } catch (e: NumberFormatException) { "Sorry users it accepts only string values" }
println(b)
a = "89"
b = try { a.toInt() } catch (e: NumberFormatException) { "Thank you users its a string value" }
println(b)
try {
var d = 9 / 0
val f = "Have a Nice Day users"
f.toInt()
} catch (e: ArithmeticException) {
println("Arthimetic Exception")
} catch (e: Exception) {
println("Exception occurred please find the stack trace print using e")
} finally {
println("Thank you for spending the time with us")
}
}
Output:
In the last example, we calculate the sorting operations, and also we have done the arithmetic operations, and we get the Arithmetic exception.
Conclusion
In kotlin language, we used additional operations and features for implementing the application; after executing the application, we got some valid exceptions and errors while the inputs were not authenticated or were not satisfied with the coding logic. With the help of the Exception concept, we can over through the exceptions, and also it accepts some customized exceptions.
Recommended Articles
This is a guide to Kotlin Exceptions. Here we discuss the introduction, syntax, and working of exceptions in kotlin along with different examples and its code implementation. You may also have a look at the following articles to learn more –