Skip to main content

Exception handling

The try-catch statement allows handling user-defined exceptions.

Syntax

try {
// Code that might throw an exception
} catch (error) {
// Handle the exception
}

throw Keyword

The throw keyword is used to manually raise exceptions in the program. When an exception is thrown, execution stops immediately, and control is passed to the nearest try-catch block that can handle the thrown exception. Only user-defined exceptions can be caught (or those thrown by libraries), and internal exceptions cannot be intercepted. The throw keyword must be followed by an expression, which can be a string, object, or any other value. If no catch block is found, the program will terminate. The thrown value can include extra information, such as error messages or codes, to support more detailed error handling.

⚠️ The standard library may throw exceptions which can be caught, so always read the documentation first!

Syntax

throw expression;

Example: Division by zero

fn divide(a, b) {
if (b == 0) {
throw "Division by zero is not allowed";
}
return a / b;
}

try {
const result = divide(10, 0);
console.log("Result: ", result);
} catch (err) {
console.log("Error: ", err); // "Error: Division by zero is not allowed"
}

Example: Throwing and Catching an Object

fn validateInput(input) {
if (input.length === 0u) { //notice the 0u when strict-comparing to length
throw { message: "Input cannot be empty", code: 400 };
}
return "Valid input";
}

try {
console.log(validateInput(""));
} catch (err) {
console.log("Error: ", err.message, ", Code: ", err.code);
}