Kotlin Exception Testing 🎯

beginner
6 min

Kotlin Exception Testing 🎯

Welcome to the Kotlin Exception Testing tutorial! In this lesson, we'll explore how to handle errors and exceptions in Kotlin, ensuring your code remains robust and functional. Let's dive in! 🐳

Understanding Exceptions in Kotlin 📝

Exceptions are events that occur during the execution of a program that disrupt the normal flow of instructions. In Kotlin, we can create our own exceptions or use built-in ones to handle errors.

Built-in Exceptions

Kotlin provides several built-in exceptions, such as:

  • IllegalArgumentException: Thrown when a method or constructor receives an illegal or inappropriate argument.
  • NullPointerException: Thrown when an application attempts to use null on an object reference, where it is not allowed.
  • IndexOutOfBoundsException: Thrown when an index or position is outside of the bounds of an array or a string.

Creating Custom Exceptions 💡

We can create custom exceptions to represent specific errors in our applications. Here's an example of creating a custom exception for invalid usernames:

kotlin
class InvalidUsernameException(message: String) : Exception(message)

Now, we can throw this exception when checking a username:

kotlin
fun checkUsername(username: String) { if (username.length < 3) { throw InvalidUsernameException("Username must be at least 3 characters long") } }

Handling Exceptions with try-catch 📝

The try-catch block allows us to handle exceptions gracefully. When an exception occurs within the try block, the program flow jumps to the appropriate catch block for handling the exception.

Here's an example using the IllegalArgumentException:

kotlin
fun calculate(a: Int, b: Int) { if (b == 0) { throw IllegalArgumentException("Cannot divide by zero") } try { val result = a / b println("Result: $result") } catch (e: IllegalArgumentException) { println("Error: ${e.message}") } }

Exception Propagation 💡

Sometimes, we may want to let exceptions bubble up to the calling method so it can handle them. This process is called exception propagation.

kotlin
fun divide(a: Int, b: Int) { if (b == 0) { throw IllegalArgumentException("Cannot divide by zero") } return a / b } fun main() { try { val result = divide(5, 0) println("Result: $result") } catch (e: IllegalArgumentException) { println("Error: ${e.message}") } }

try-catch-finally 📝

The finally block is used to execute code after the try and catch blocks, regardless of whether an exception was thrown or not. This is useful for cleaning up resources, like closing file handles.

kotlin
fun openFile(filename: String): BufferedReader? { var reader: BufferedReader? = null try { reader = FileReader(filename).bufferedReader() } catch (e: FileNotFoundException) { println("Error: ${e.message}") return null } return reader } fun main() { val reader = openFile("non_existent_file.txt") if (reader != null) { reader.close() } }

Rethrowing Exceptions 💡

If we catch an exception but cannot handle it, we can rethrow it for the calling method to handle.

kotlin
fun divide(a: Int, b: Int): Int { if (b == 0) { throw IllegalArgumentException("Cannot divide by zero") } return a / b } fun checkDivisibility(a: Int, b: Int) { if (b % 2 == 0) { throw IllegalArgumentException("B must be an odd number") } try { val result = divide(a, b) println("Result: $result") } catch (e: IllegalArgumentException) { throw e } }

Quiz

Quick Quiz
Question 1 of 1

Which built-in exception is thrown when an application attempts to use `null` on an object reference, where it is not allowed?

We hope you enjoyed learning about Kotlin Exception Testing! As you can see, exception handling is crucial for creating robust, reliable, and user-friendly applications. Happy coding! 🌟