In TypeScript, exception handling is done using the ‘try‘, ‘catch‘, and ‘finally‘ constructs, similar to JavaScript. Here’s a brief explanation of each construct:
- ‘try‘: Wraps the code that might throw an exception.
- ‘catch‘: Captures the exception thrown by the code inside the ‘try‘ block and contains a block of code to execute when an exception occurs.
- ‘finally‘: Contains a block of code that will always execute regardless of whether an exception occurs or not.
Here’s an example illustrating the use of ‘try‘, ‘catch‘, and ‘finally‘:
function divide(a: number, b: number): number {
let result: number;
try {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
result = a / b;
} catch (error) {
console.error(`Error: ${error.message}`);
result = NaN; // return NaN if an error occurs
} finally {
console.log("Division operation executed");
}
return result;
}
console.log(divide(4, 2)); // 2
console.log(divide(4, 0)); // NaN
function divide(a: number, b: number): number {
let result: number;
try {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
result = a / b;
} catch (error) {
console.error(`Error: ${error.message}`);
result = NaN; // return NaN if an error occurs
} finally {
console.log("Division operation executed");
}
return result;
}
console.log(divide(4, 2)); // 2
console.log(divide(4, 0)); // NaN
In this example, the ‘divide‘ function takes two numbers as input and returns their quotient. Inside the ‘try‘ block, we check if the divisor is zero and throw an error if it is. The ‘catch‘ block captures the error, logs its message, and assigns ‘NaN‘ to the ‘result‘ variable. The ‘finally‘ block logs a message indicating that the division operation was executed. The function then returns the result.