Exception handling
The try-catch
statement allows handling user-defined exceptions.
- No
finally
block: Cleanup operations must be handled manually. - Only user-defined exceptions can be caught: Internal exceptions (such as syntax errors or out-of-memory errors) cannot be intercepted.
⚠️ The standard library may throw exceptions which can be caught, so always read the documentation first!
- The
catch
block requires a parameter: Omitting the parameter results in a syntax error.
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.
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 === 0) {
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);
}
Notes
throw
must be followed by an expression, which can be a string, object, or any other value.- When an exception is thrown, the program will stop executing the current function and look for a
catch
block to handle it. - If no
catch
block is found, the program will terminate. - The thrown object can contain additional details, such as error codes or messages, for more advanced error handling.