try / handle / finally

Handle checked Java exceptions and run final cleanup.

Example.kalm
use java.nio.file.Files
use java.nio.file.Path

pub fun readFile(path: Path) -> Text:
    try:
        return Files.readString(path)
    handle (error: java.io.IOException):
        return "Could not read file"
    finally:
        sayLine("read attempted")
Example.kalm
use java.nio.file.Files
use java.nio.file.Path

pub fun readFile(path: Path) -> Text {
    try {
        return Files.readString(path)
    }
    handle (error: java.io.IOException) {
        return "Could not read file"
    }
    finally {
        sayLine("read attempted")
    }
}
Example.kalms
use java.nio.file.Files
use java.nio.file.Path

fun readFile(path: Path) -> Text:
    try:
        return Files.readString(path)
    handle (error: java.io.IOException):
        return "Could not read file"
    finally:
        sayLine("read attempted")
Example.kalms
use java.nio.file.Files
use java.nio.file.Path

fun readFile(path: Path) -> Text {
    try {
        return Files.readString(path)
    }
    handle (error: java.io.IOException) {
        return "Could not read file"
    }
    finally {
        sayLine("read attempted")
    }
}
Example.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public final class Example {
    public static String readFile(Path path) {
        try {
            return Files.readString(path);
        } catch (IOException error) {
            return "Could not read file";
        } finally {
            System.out.println("read attempted");
        }
    }
}

Learn more.