Keywords in Exception Handling
In exception handling, there are four different keywords. These are the following:
try, catch, finally, throw
- try: The try block comprises a series of statements that may result in an exception. So, either catch or finally, or both, must come after it.
- catch: The try block throws an exception, which is caught by the catch block.
- finally: It contains code that should be run regardless of whether or not an exception occurs.
- throw: The term(throw is a keyword in Kotlin) throw is used to explicitly throw an exception.
1. Try-Catch Block and It's Need
Before looking at the syntax of our exception handling, first, let us understand the need for it and the outcome without it.
Run this set of lines on your compiler.
Code:
fun main() {
var x = 15 / 0
println(x)
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Here, We have initialized a var x with the value of 15/0, But since we know in arithmetic that anything divided by zero is not allowed. So, as we try to run our program, it throws an arithmetic exception on run-time, and program execution stops.
So to avoid this issue, we have to use exception handling. The syntax of the try-catch block is given below.
Syntax:
try{
// writing our code/program that may throw exception
}catch(e: SomeException){
// catch followed by try, containing code to catch and handle exception
}
Now, let's solve 15 / 0 arithmetic exception using try-catch.
Code:
fun main() {
try{
var x = 15 / 0
}
catch(e: ArithmeticException){
println("Exception Handled: Dividing anything by zero is not allowed")
}
}
Output:
Exception Handled: Dividing anything by zero is not allowed
Kotlin try-catch block as an expression
Expressions, as we all know, always yield a value. In our program/code, we can use the kotlin try-catch block as an expression. The value returned by the expression will be either the last try block expression or the last catch block expression. If no exception occurs, then the value is returned by try block, and If an exception occurs in the code, the value is returned by the catch block. Here is an example:
Code:
fun main(){ // compiler searches for main()
var x= test(15,5) // Function call test() and try block is executed
println(x)
var y= test(15,0) // Function call test() and catch block is executed
println(y)
}
fun test(a: Int, b: Int) : Any {
return try {
a/b // returns value of a/b to main()
}
catch(e:Exception){
println(e)
"Arithmetic error :Dividing anything by zero is not allowed"
}
}
Output:
3
java.lang.ArithmeticException: / by zero
Arithmetic error :Dividing anything by zero is not allowed
Here, the compiler goes to main(), creates var x, and calls test() with arguments a/b as 15/5, which is executable. So, try returns a/b, which is 3.
Then var y is created and calls to test() with 15,0 as arguments. Now, In the expression a/b, 15/0 creates an arithmetic exception. As a result, the catch block is executed.
2. Kotlin finally block
Whether or not the catch block handles an exception, the finally block is always executed in Kotlin. As a result, it's used to run crucial code statements.
As per our need, We can combine try and finally blocks and skip the catch block, or We can use all try-catch and finally blocks.
Syntax of try-finally block
The format for the syntax of try-finally block will be like.
Code:
try {
// write codes which can throw exception
} finally {
// write finally block codes
}
Let us see try-finally block implementation with this simple example.
Example P1:
Code:
fun main(){
try{
var my_arr = arrayOf(10, 20, 30)
var x = my_arr[2]
println(x)
}
finally {
println("This finally block is always executed in Kotlin")
}
}
Example P2:
Code:
fun main(){
try{
var my_arr2 = arrayOf(10, 20, 30)
var x2 = my_arr2[5]
println(x2)
}
finally {
println("This finally block is always executed in Kotlin")
}
}
In Program P1, the array my_arr is created with three values 10, 20, 30 in it in the try block. The third element with index 2 is accessed, and its value gets printed, and the block finally gets executed.
So the output of P1 will be
Output:
30
This finally block is always executed in Kotlin
In Program P2, In the try block array, my_arr2 is created with three values 10, 20, 30 in it. The sixth element with index 5 is tried to access. Since it is not present, the index out of bounds exception occurs but finally block still gets executed.
So the output of P2 will be
Output:
This finally block is always executed in Kotlin
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
Syntax of try-catch-finally block
Syntax:
try {
// write codes which can throw exception
} catch(e: SomeException) {
// exception catch and handling
} finally {
// write finally block codes
}
Let’s use finally with try-catch in arithmetic exception query of dividing value by 0.
Code:
fun main(){
try {
var x = 15 / 0
println(x)
} catch (e: ArithmeticException) {
println(e)
} finally {
println("This finally block is always executed in Kotlin")
} }
Here in the main(), We enter into the try block and notice 15 / 0 given to variable x, which throws an exception. The catch block handles the exception, and then finally, the block is executed. So the output will be
Output:
java.lang.ArithmeticException: / by zero
This finally block is always executed in Kotlin
3. Kotlin throw keyword
the throw keyword is used in Kotlin for throwing an explicit exception, and it can even be used for throwing a custom exception.
Here is an example of entering a user name for a website, where we use throw keyword-
Code:
fun main(){
checkUserName("Ani") // length of Ani is 3
println("valid userName entered, you can proceed further")
}
fun checkUserName(userName: String) {
if (userName.length < 4)
throw ArithmeticException("userName is too short")
else
println("valid userName")
}
Here, the user entered "Ani" as the user name, which has a string length of 3(< 4). As a result, the arithmetic exception occurs, and only "userName is too short" gets printed.
Output:
Exception in thread "main" java.lang.ArithmeticException: userName is too short
When the user enters “CodingNinjas”, Since “CodingNinjas” has a string length of 12(> 4) so the else statement is executed and the compiler returns back to main() and processes your code.
Code:
fun main(){
checkUserName("CodingNinjas") // length of codingNinjas is 12
println("valid userName entered, you can proceed further")
}
fun checkUserName(userName: String) {
if (userName.length < 4)
throw ArithmeticException("userName is too short")
else
println("valid userName")
}
Output:
valid userName
valid userName entered, you can proceed further
FAQs
-
Does Kotlin support the checked exceptions?
Checked exceptions are not supported in Kotlin since the language's creators concluded that they're more hassle than they're worth. So, this language supports unchecked exceptions only.
-
Why do we need exception handling?
Without exception handling, a Crash will happen every time an exception occurs in our code. So, to prevent this, exception handling is a must.
-
Can we throw an exception manually?
Yes, we may manually throw an exception with the throw keyword.
-
What is the difference between error and exception?
The environment where an application is running is the primary cause of errors, like OutOfMemoryError, And exceptions are primarily caused by the application itself, like NullPointerException.
Key Takeaways
Cheers on reaching here!
The purpose of this article was to introduce the reader to the Kotlin Maps, HashMap and give some basic ideas about how to initialize and use them with their properties and functionalities.
If anyone wants to set up their Kotlin environment for programming, then here is the help.
However, learning never stops, and there is more to learn. So head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications. Till then, Happy Learning!