Exceptions
Exceptions manage error handling deterministically in Autolang. Autolang supports custom exception classes, typed catch blocks, try expressions, and guaranteed finally cleanup.
Throwing & Catching Exceptions
Throw errors using the throw keyword. Thrown values must inherit from the base Exception class. Handle thrown errors using try, one or more catch blocks, and an optional finally block.
fun verifyOrderAmount(amount: Int) {
if (amount <= 0) {
throw Exception("Invalid order amount: " + amount)
}
}
try {
verifyOrderAmount(-50)
} catch (e) {
println("Caught validation error: " + e.message)
}Typed Catch Blocks
Autolang supports multiple typed catch branches. Each branch matches a specific exception subclass, with an optional catch-all branch at the end.
class ValidationException extends Exception {
val fieldName: String
constructor(msg: String, field: String) {
super(msg)
this.fieldName = field
}
}
class NetworkTimeoutException extends Exception {
constructor(msg: String) { super(msg) }
}
fun executeOperation(kind: Int) {
if (kind == 1) throw ValidationException("Missing billing address", "billing_address")
if (kind == 2) throw NetworkTimeoutException("Gateway did not respond in 5000ms")
throw Exception("Generic execution error")
}
try {
executeOperation(1)
} catch (e: ValidationException) {
println("Field error on " + e.fieldName + ": " + e.message)
} catch (e: NetworkTimeoutException) {
println("Network failure: " + e.message)
} catch (e) {
println("Fallback error: " + e.message)
}Try as an Expression
try blocks can evaluate to values directly. The last evaluated line in the completed try or catch branch is returned.
fun parseStatusCode(rawInput: String): Int {
return try {
rawInput.toInt()
} catch (e) {
500 // Fallback status code
}
}
println("Parsed status: " + parseStatusCode("200")) // 200
println("Fallback status: " + parseStatusCode("invalid")) // 500Finally Blocks & Guaranteed Cleanup
The finally block executes regardless of whether an exception was thrown, caught, or whether the try block executed a return statement. This ensures deterministic resource cleanup.
var resourceClosed = false
fun processWorkflow(): String {
try {
println("Executing critical capability...")
return "SUCCESS"
} catch (e) {
return "FAILED"
} finally {
resourceClosed = true
println("Resource successfully released in finally")
}
}
val outcome = processWorkflow()
println("Workflow outcome: " + outcome)
println("Cleaned up? " + resourceClosed)