WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TypeScript · Intermediate · question 27 of 100

How do you handle exceptions in TypeScript? Can you give an example of try/catch/finally?

📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TypeScript interview — then scores it.
📞 Practice TypeScript — free 15 min
📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

All 100 TypeScript questions · All topics