Section 1.13 Exception Handling
There are three types of errors that typically occur when writing programs. The first, known as a syntax error, simply means that the programmer has made a mistake in the structure of a statement or expression. For example, putting these arithmetic operators together:
fun main() {
val n = 2 + * 3
println(n)
}
results in this error:
Kotlin: Syntax error: Expecting an element.
In this case, the Kotlin compiler has found that it cannot complete the processing of this statement since it does not conform to the rules of the language. Syntax errors are usually more frequent when you are first learning a language.
Another type of error, known as a run time error, happens when the syntax is correct, but the program cannot execute correctly:
fun main() {
val n = 12 / 0
println(n)
}
Exception in thread "main" java.lang.ArithmeticException: / by zero at RuntimeErrorExampleKt.main(RuntimeErrorExample.kt:2) at RuntimeErrorExampleKt.main(RuntimeErrorExample.kt)
Aside: Why does this error mention Java?
The last type of error, known as a logic error or semantic error, denotes a situation where the program executes but gives the wrong result. This can be due to an error in the underlying algorithm or an error in your translation of that algorithm. For example, the following code for computing the area of a rectangle uses correct Kotlin syntax, and the arithmetic will not cause a run-time error, but the logic is wrong; area is length times width, not length plus width:
val length = 25
val width = 15
val area = length + width
println(area)
In some cases, logic errors can lead to errors such as trying to divide by zero or trying to access an item in a list where the index of the item is outside the bounds of the array. In this case, the logic error leads to a runtime error that causes the program to terminate. These types of runtime errors are typically called exceptions.
Most of the time, beginning programmers think of exceptions as fatal runtime errors that cause the end of execution. However, most programming languages provide a way to deal with these errors that will allow the programmer to have some type of intervention if they so choose. In addition, programmers can create their own exceptions if they detect a situation in the program execution that warrants it.
When an exception occurs, we say that it has been thrown or raised. You can handle the exception that has been raised by using a
try statement. For example, consider the following program that asks the user for an integer and then tries to access an array element at that index.
fun main() {
val data = listOf(10, 66, 47, 11, 505, 217)
print("Enter an index: ")
val index = readln().toInt()
val value = data[index]
println("The element is $value.")
}
If the user enters a positive value that is less than the array length, the
println() will display the value. However, if they enter a negative number or a number greater than or equal to the array length, the program will report an ArrayIndexOutOfBounds exception.
Enter an index: 7 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 6 at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4266) at BadIndexOnListKt.main(BadIndexOnList.kt:7) at BadIndexOnListKt.main(BadIndexOnList.kt)
We can handle this exception by calling the
println function from within a try block. A corresponding catch block βcatchesβ the exception and prints a message back to the user in the event that an exception occurs. Here is the modified program:
fun main() {
val data = listOf(10, 66, 47, 11, 505, 217)
print("Enter an index: ")
val index = readln().toInt()
try {
val value = data[index]
println("The element is $value.")
} catch (e: Exception) {
println("Index must be from 0 to ${data.count()}.")
}
}
Now, if the user enters a number out of range, the program will catch the exception raised by the array access and will instead print a useful error message. This means that the program will not terminate but instead will continue on to the next statements.
Enter an index: 7 Index must be from 0 to 6.
The
e variable is an Exception object, and Kotlin provides methods to allow programmers to extract information about the exception, such as an error message, the βstack traceβ (the sequence of calls that happened when the exception occurred), and other information.
It is also possible for a programmer to cause a runtime exception by using the
throw statement. For example, letβs say a method cannot calculate a valid return value if given a negative number. Instead of printing an error message βwhich may not be appropriate in a general-purpose library β it will throw an IllegalArgumentException and let the code that callled the method handle it with a catch:
fun doCalculation(n: Double): Double {
if (n > 0) {
// a complicated calculation goes here
return ...
} else {
throw IllegalArgumentException("$n cannot be negative.")
}
}
The string in the
throw statement will be the message associated with the exception.
There are many kinds of exceptions that can be raised in addition to the
IllegalArgumentException shown above. See the Kotlin API for a list of some of the exception types.
You have attempted of activities on this page.

