Skip to content

Using `finally` with `try catch` in Kotlin

Kotlin, Error Handling1 min read

When writing robust code, it's crucial to handle errors gracefully and ensure proper cleanup of resources. Kotlin provides powerful mechanisms for error handling, including the try catch statement. Additionally, we have the finally block, which offers a way to specify code that should execute regardless of whether an exception is thrown or not. In this article, we will explore how to use finally with try catch in Kotlin, along with some practical examples.

Basic Syntax

The basic syntax for using finally with try catch in Kotlin is as follows:

1try {
2 // Code that may throw an exception
3} catch (e: Exception) {
4 // Exception handling logic
5} finally {
6 // Code that always executes, regardless of whether an exception occurred or not

The try block contains the code that might throw an exception. If an exception occurs within the try block, it is caught by the corresponding catch block, where you can handle the exception as needed. The finally block comes after the catch block and contains code that will be executed regardless of whether an exception was thrown or not.

Example: File Handling

Let's consider an example where we need to open a file, read its contents, and ensure that the file is closed properly, even in the presence of exceptions. Here's how we can achieve this using finally with try catch in Kotlin:

4fun readFileContent(fileName: String): String {
5 val file = File(fileName)
6 try {
7 // Open the file
8 val content = file.readText()
9 // Process the file content
10 return content
11 } catch (e: IOException) {
12 // Handle file-related exceptions
13 println("An error occurred while reading the file: ${e.message}")
14 } finally {
15 // Close the file in all cases
16 file.close()
17 }

In the code above, we attempt to read the contents of a file specified by its name. If an IOException occurs during the file reading process, we handle it in the catch block. However, regardless of whether an exception occurred or not, we ensure that the file is closed properly by invoking the close() method within the finally block.

Example: Database Transaction

Another common scenario where finally with try catch is useful is database transactions. Suppose we have a function that performs some database operations within a transaction. We want to make sure that the transaction is always committed or rolled back appropriately, even if an exception occurs. Here's an example that demonstrates this:

1import java.sql.Connection
2import java.sql.DriverManager
3import java.sql.SQLException
5fun performDatabaseTransaction() {
6 val connection: Connection = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password")
8 try {
9 // Start the transaction
10 connection.setAutoCommit(false)
12 // Perform database operations
13 // ...
15 // Commit the transaction
16 connection.commit()
18 } catch (e: SQLException) {
19 // Handle database-related exceptions
20 println("An error occurred while performing the database transaction: ${e.message}")
21 // Rollback the transaction
22 connection.rollback()
24 } finally {
25 // Reset auto-commit to true and close the connection
26 connection.autoCommit = true
27 connection.close()
28 }

In this example, we establish a database connection and initiate a transaction. If any SQLException occurs during the transaction, we handle it in the catch block and rollback the changes. The finally block ensures that we reset the auto-commit flag to true and close the connection, ensuring proper cleanup.

In Closing

Using the finally block with try catch statements in Kotlin allows for effective error handling and resource cleanup. By leveraging the power of finally, you can ensure critical code always executes regardless of exceptions. Whether you're working with file I/O, database transactions, or other scenarios, incorporating finally into your error-handling strategy will make your code more robust.