TypeScript Exception Handling



Exception Handling in TypeScript

TypeScript has a limited support for Exception Handling because catching exceptions in JavaScript is, compared to some kinds of exceptions in Java, optional.

Rule(s)

Example Temperature.js.zip 

function Invalid_temperature_exception(value) {
    this._message = "Invalid temperature";
    this._value = value;
}
…
throw new Invalid_temperature_exception(this._value);
…
try {
    const t1 = new Temperature(-1, Temperature_unit.Kelvin);
} catch (ite) {
    window.alert(ite._message + ": physics' laws prevent -1°K...");
} finally {
    window.alert("'finally' as in Java...");
}

Rule(s)

Example (user-defined exception type) Temperature.ts.zip 

class Invalid_temperature_exception extends Error { // Inheriting from JavaScript root type for exceptions...
    constructor(private readonly _value, ...params) {
        // Pass remaining arguments to parent constructor:
        super(...params)
    }
    // 'message' is an attribute inside 'Error' and thus cannot be overridden as a method here:
    public getMessage(): string {
        return this.constructor.name + ": " + this._value;
    }
}

Example (throwing) Temperature.ts.zip 

public decrement(): never | void { // 'Temperature' instance method...
    this._value -= this._step;
    if (this._value < Temperature.Min) {
        throw new Invalid_temperature_exception(this._value);
    }
    console.assert(this._value >= Temperature.Min);
}

Example (catching) Temperature.ts.zip 

const t__ = new Temperature(0., Temperature_unit.Kelvin);
// try {
//     t__.decrement();
// } catch (ite: any) { // Eventually, no type checking...
//     window.confirm(ite.getMessage());
// }
try {
    t__.decrement();
} catch (ite: unknown) { // Signature is from TypeScript 4.x only!
    window.confirm((ite as Invalid_temperature_exception).getMessage()); // Cast is imposed by 'unknown'...
}