Exceptions
Exceptions are used to handle runtime errors gracefully without crashing the virtual machine.
Throwing Exceptions
Use the throw keyword to throw an exception. The thrown object must be an instance of the Exception class or a class that extends it.
fun test() {
throw Exception("Something went wrong")
}
try {
test()
} catch (e) {
println("Caught error: ${e.message}")
}Try / Catch
Use try and catch to handle exceptions and prevent your program from terminating.
try {
val zero = 0
val x = 10 / zero
} catch (e) {
println("Error: ${e.message}")
}
// Another example
try {
println("Start")
throw Exception("A fatal error occurred")
} catch (e) {
println("Caught: ${e.message}")
}⚠️ Catch Type Constraint
The exception variable is always treated as the base Exception type. Writing explicit types like catch (e: CustomException) is forbidden by the compiler.
Handling Custom Exceptions
Since you can only catch the base Exception, use the is operator to check the specific error type at runtime.
class SkillIssueException extends Exception {
constructor(message: String) {
super(message)
}
}
try {
throw SkillIssueException("Developer forgot to drink coffee")
} catch (e) {
if (e is SkillIssueException) {
println("Skill Issue detected: ${e.message}")
} else {
println("Unknown error: ${e.message}")
throw e
}
}Rethrowing
If you catch an exception but cannot handle it in the current scope, you can throw e again to pass it up the call stack.
fun riskyOperation() {
try {
throw Exception("Database connection failed")
} catch (e) {
println("Logging error internally...")
throw e // Rethrow to the caller
}
}
riskyOperation()Location-Aware Exceptions
Autolang does not generate heavy stack traces automatically. You can combine Exceptions with Magic Constants to track exactly where an error occurred.
class LoggedException extends Exception {
constructor(message: String, file: String, line: Int) {
super("[${file}:${line}] ${message}")
}
}
fun parseData() {
try {
throw LoggedException("Failed to parse JSON", __FILE__, __LINE__)
} catch (e) {
println("Critical Error: ${e.message}")
}
}
parseData()
// Output: Critical Error: [index.atl:12] Failed to parse JSON