CodeGym /Courses /Kotlin SELF /try/catch around file operations

try/catch around file operations

Kotlin SELF
Level 45, Lesson 2
Available

1. Why try/catch is needed even after pre-checks

When you start doing pre-checks for the first time, you get the feeling: “That’s it, I checked exists() and canRead() — so I can read!” And here Kotlin (and the OS) gently remind you: “ha-ha, nope.” Pre-checks only say that at the moment of the check everything looked OK. But the real operation readText() is an actual attempt to read data, and it still can end with an exception.

Imagine a simple situation: you checked exists() == true, and a millisecond later the file was deleted (or renamed) by another process/user. This is not science fiction — this is normal life on a computer.

import java.io.File

fun main() {
    val file = File("data/input.txt")

    if (file.exists()) {
        // Between exists() and readText() the file may disappear.
        val text = file.readText()
        println("OK: ${text.length}") // if you are lucky
    }
}

If you are not lucky, you will get an exception during the read. And that is normal: try/catch is not a replacement for pre-checks, but a second barrier, which must be placed around real I/O.

2. Narrow try: only real I/O goes inside

The most common beginner mistake looks like this: “I’ll wrap everything in one big try so it definitely won’t crash.” That is like putting a bulletproof vest on a fridge: heavy, uncomfortable, and the fridge does not care anyway. A big try makes the code muddy: it is unclear what exactly could have broken, and in catch you often try to “continue somehow” without understanding what state the data is in.

Anti-example: a too-wide try.

import java.io.File
import java.io.IOException

fun main() {
    val file = File("data/amount.txt")

    try {
        val text = file.readText()
        val amount = text.trim().toInt() // this is NOT I/O anymore; this is data format
        println("amount=$amount")
    } catch (e: IOException) {
        println("Failed to read the file")
    }
}

The problem here is subtle: toInt() can throw NumberFormatException, and it is not an IOException. So the program will still crash, but “somehow weirdly”: you “wrapped everything,” right? But you did not wrap everything — only the I/O part.

It is better to split responsibilities: reading a file is I/O and is handled as IOException, while parsing text is already a “data/format error” and should live separately (even if today we are focusing specifically on I/O).

import java.io.File
import java.io.IOException

fun readTextOrNull(file: File): String? =
    try {
        file.readText()
    } catch (e: IOException) {
        null
    }

fun main() {
    val file = File("data/amount.txt")

    val text = readTextOrNull(file) ?: run {
        println("File was not read: ${file.path}")
        return
    }

    val amount = text.trim().toIntOrNull()
    println("amount=$amount") // amount=123 or amount=null
}

Notice how the code feels: reading is separated, try is narrow, and then you calmly decide what to do with the contents.

A small “responsibility map” is useful even in console projects:

flowchart TD
    A[CLI / main] --> B["loadRawText()"]
    B -->|I/O: readText| C[(File)]
    B -->|String? / error| A
    A --> D[parse / validate]
    D -->|format error| A

3. try as an expression: return a value instead of “falling apart”

Kotlin can do something that makes error handling noticeably nicer: try/catch is an expression, meaning it can return a value. This lets you write functions with a clear contract: “if it worked, I return the result; if it did not, I return a fallback.” In Kotlin, this style is considered idiomatic: try returns one value, catch returns another.

The simplest option for reading a file: “text or null”.

import java.io.File
import java.io.IOException

fun readTextOrNull(file: File): String? = try {
    file.readText()
} catch (e: IOException) {
    null
}

fun main() {
    val file = File("data/input.txt")

    val text = readTextOrNull(file)
    println(text?.take(20) ?: "NO DATA") // for example: NO DATA
}

In the same way, for writing you can choose the contract “success/failure”.

import java.io.File
import java.io.IOException

fun writeTextSafely(file: File, text: String): Boolean = try {
    file.writeText(text)
    true
} catch (e: IOException) {
    false
}

fun main() {
    val ok = writeTextSafely(File("data/out/report.txt"), "Hello!\n")
    println("written=$ok") // written=true or written=false
}

This idea seems simple, but it disciplines the program: instead of hoping “it won’t crash,” you design in advance: what we return when there are problems.

4. Function contract for I/O: T?, Boolean, or rethrowing an exception

When you put try/catch in place, you always make a decision: what will the calling code see? For educational console apps, three contracts are usually enough: return T?, return Boolean, or do not catch the exception here and let it bubble up (sometimes that is also a valid strategy).

It helps to keep this comparison in mind like a table:

Function contract What it looks like When it is convenient Cost of a mistake
T?
String?, List<String>?
When absence of a result is a normal branch of logic You must remember to handle
null
Boolean
true/false
When you do not need the data, only whether it “worked” Weaker diagnostics: why
false
?
Rethrow the exception without try/catch (or throw it further) When the program makes no sense without the file The program may crash if nothing above handles it

Important: we do not choose “the one correct way forever”. We choose what is more convenient in your application and at this point in the code.

For example, in our educational console app let it be a simple “expense jar”: we store expenses in a text file and show a short report. If the file cannot be read, we can show a clear message and start with an empty list — a great candidate for the List<String>? contract.

import java.io.File
import java.io.IOException

fun readLinesOrNull(file: File): List<String>? = try {
    file.readLines()
} catch (e: IOException) {
    null
}

fun main() {
    val file = File("data/expenses.txt")
    val lines = readLinesOrNull(file) ?: emptyList()

    println("loaded=${lines.size}") // loaded=0 if the file is missing/not readable
}

But writing the report can be done as Boolean: if it was not written, we just report it.

5. Error messages: for the user and for you

An error message is not a work of art and not “something went wrong.” A good message answers at least three questions: what you wanted to do, with what exactly (path), and what type of problem it was. Even without a logging system, this already helps a lot.

It is useful to create a small message formatter for I/O. It does not have to be smart — it has to be stable and consistent across the app.

import java.io.File
import java.io.IOException

fun ioErrorMessage(action: String, file: File, e: IOException): String {
    val type = e::class.simpleName ?: "IOException"
    val detail = e.message ?: "no details"
    return "Failed to $action: ${file.path}. Cause: $type: $detail"
}

And use it in catch:

import java.io.File
import java.io.IOException

fun readTextOrNullVerbose(file: File): String? = try {
    file.readText()
} catch (e: IOException) {
    println(ioErrorMessage("read file", file, e))
    null
}

fun main() {
    val text = readTextOrNullVerbose(File("data/input.txt"))
    println(text?.length ?: "no text") // no text
}

Yes, we print directly to the console — and that is fine for an educational CLI. In more serious projects, you would separate “a message for the user” and “diagnostics for logs,” but today we intentionally do not go into logging.

Multiple catch blocks: order and why to split

Sometimes you want to catch everything with one catch (IOException). That is fine, but it is often useful to distinguish at least one special case: “file not found / cannot be opened,” i.e. FileNotFoundException. Then you can provide a more human-friendly text: “check the path” instead of “oops, I/O.”

Rule in Kotlin (and generally on the JVM): catch the more specific first, then the more general, otherwise the specific one will never run.

import java.io.File
import java.io.FileNotFoundException
import java.io.IOException

fun main() {
    val file = File("data/input.txt")

    try {
        val text = file.readText()
        println("OK: ${text.length}") // OK: ...
    } catch (e: FileNotFoundException) {
        println("File not found or cannot be opened: ${file.path}")
    } catch (e: IOException) {
        println("I/O error while reading: ${file.path}")
        println("Details: ${e.message}")
    }
}

It is important not to overcomplicate: we split out only the most common case, and left everything else under IOException.

6. Where to put try/catch: the responsibility boundary

It is very tempting to catch exceptions in main, because “everything is visible there.” But as an application grows, it turns into a huge all-in-one machine: main reads input, parses commands, works with data, and also catches every possible problem. Good style is to catch I/O where it happens, and return an understandable result outward.

For our expense tracker, this means: storage functions themselves wrap readText()/writeText() in try/catch, and main receives either data or a “did not work” signal.

The diagram is simple:

flowchart TD
    M[main: user commands] --> S[storage: read/write file]
    S -->|List⟨String⟩? / Boolean| M
    S -->|IOException inside| S

An example of a mini storage layer (no “magic,” everything is short and explicit):

import java.io.File
import java.io.IOException

fun loadExpensesOrNull(file: File): List<String>? = try {
    file.readLines()
} catch (e: IOException) {
    null
}

fun saveExpenses(file: File, lines: List<String>): Boolean = try {
    file.writeText(lines.joinToString(separator = "\n"))
    true
} catch (e: IOException) {
    false
}

And using it in main without feeling like you are running a nuclear power plant:

import java.io.File

fun main() {
    val file = File("data/expenses.txt")

    val lines = loadExpensesOrNull(file)
    if (lines == null) {
        println("Failed to load expenses; starting with an empty list.")
    } else {
        println("Loaded records: ${lines.size}") // for example: Loaded records: 12
    }
}

Psychologically, this is an important thing: main does not have to know exactly how the OS refused to read. main has to make a decision: continue with empty data, ask the user to fix the path, exit — and so on.

7. finally and use {}: when they are needed

The word finally often sounds like “a secret Jedi technique.” In reality, it is needed for exactly one thing: to guarantee that a certain piece of code runs at the end, even if an error occurred inside try. In file tasks, this is especially important for closing resources if you open streams/readers manually.

But Kotlin provides an even more convenient style: use {}, which automatically closes the resource (roughly like finally, but cleaner). This is considered the idiomatic approach for AutoCloseable.

We will not dive into streams today, but a small example is useful to see the boundary: readText() does not require use, but bufferedReader() does.

import java.io.File
import java.io.IOException

fun readFirstLineOrNull(file: File): String? = try {
    file.bufferedReader().use { reader ->
        reader.readLine()
    }
} catch (e: IOException) {
    null
}

fun main() {
    val first = readFirstLineOrNull(File("data/input.txt"))
    println(first ?: "<empty>") // for example: <empty>
}

Remember a simple rule: if you see ...Reader(), ...Writer(), InputStream, OutputStream — almost always use {} should be nearby (or, at least, finally). If you use “ready-made” functions like readText()/writeText(), they open and close resources internally, and you do not need to write finally manually.

A small Kotlin 2.x nuance: the compiler got better at tracking smart-cast information through catch/finally, so in some scenarios it more carefully hints where a variable becomes nullable again. This relates to improvements in exception handling in K2.

8. Common mistakes with try/catch around file operations

Mistake #1: a huge try that contains file reading, data parsing, and half the business logic.
Such code is unpleasant because you lose understanding of the failure cause: is it I/O, is it format, is it your logic? Plus, in catch you get the temptation to “finish something,” even though the data might not have loaded. The fix is simple: move I/O into small functions and keep try narrow — around readText()/writeText() and closely related operations.

Mistake #2: “silencing” an exception quietly.
Returning null or false is fine, but if you do not report anything at all, then with a real problem you will debug “why is it empty” instead of “why did it fail to read.” Even in an educational CLI, it is useful to print at least once: action, path, e.message. Otherwise diagnostics turns into guesswork.

Mistake #3: catching Exception “just in case.”
It looks like caring about stability, but more often it is sweeping under the rug: you start mixing I/O errors, format errors, and your own bugs. As a result, the program “kind of works,” but behaves strangely. For files, keep the focus on IOException (and sometimes FileNotFoundException as a special case), and do not hide other errors without a reason.

Mistake #4: returning Boolean but providing no information about “why false.”
Boolean is convenient when you only care about the fact of success. But if you sometimes need to understand the reason, you can (for today) at least print a message inside catch, or return null/String? with the error text. The main thing is not to create an API where false means ten different reasons, and you have no way to find out which one.

Mistake #5: incorrect catch order.
If you write catch (e: IOException) first, and then catch (e: FileNotFoundException), the second block becomes unreachable, because FileNotFoundException is a special case of IOException. The order must be “specific first, general second,” as in the classic rules of exception handling.

Mistake #6: continuing to use data after an unsuccessful read.
This is a subtle bug: you caught an exception, printed “failed,” but the variable remained, for example, an empty string, and then you parse it as if it were the file contents. You end up with a secondary error (for example, NumberFormatException) and get confused about what actually broke. If the read failed — return null/false and stop that execution path explicitly.

Mistake #7: treating canRead()/canWrite() as a guarantee.
These checks are useful, but they do not promise success: permissions can change, the file can be locked, the file system can “drop out,” and so on. So the correct combination looks like this: pre-checks improve messages and early failure, and try/catch insures the real operation.

1
Task
Kotlin SELF, level 45, lesson 2
Locked
Note preview
Note preview
1
Task
Kotlin SELF, level 45, lesson 2
Locked
Reliable write
Reliable write
1
Task
Kotlin SELF, level 45, lesson 2
Locked
Log message
Log message
1
Task
Kotlin SELF, level 45, lesson 2
Locked
Amount from a file
Amount from a file
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION