Lesson 09 of 16

Error Handling

try / catch

download this lesson (.md) ↓ all lessons

9. Error Handling

Wrap code that might fail in try { ... } catch (e) { ... }. If anything in the try block raises a runtime error, execution jumps to catch and e holds the error message (a string).

try {
    let x = 10 / 0;        // division by zero is a runtime error
    print("never reached");
} catch (e) {
    print("Caught error:", e);   // Caught error: Sıfıra bölme hatası
}
print("program continues");

The error variable is optional

try {
    let a = [1, 2];
    let bad = a[99];       // index out of bounds
} catch {
    print("something went wrong");
}

Common catchable errors

  • Division / modulo by zero
  • List/string index out of bounds
  • Undefined variable or function
  • Calling a method that does not exist
  • Wrong operand types for an operator

Using it for safe parsing

func safeDivide(a, b) {
    try {
        return a / b;
    } catch (e) {
        return null;        // signal failure
    }
}
print(safeDivide(10, 2));   // 5
print(safeDivide(10, 0));   // null

Validating input

func parseAge(text) {
    try {
        let n = int(text);
        if (n < 0) { return "negative not allowed"; }
        return n;
    } catch (e) {
        return "not a number";
    }
}
print(parseAge("25"));    // 25

Next: Modules & Packages