Skip to content
Home » Introduction to TypeScript: Enhancing JavaScript Development » Module 3: Functions and Control Flow – Orchestrating Your TypeScript Code » 3.3 Error Handling in TypeScript: Gracefully Managing Issues

3.3 Error Handling in TypeScript: Gracefully Managing Issues

Error handling is an essential aspect of any programming language, and TypeScript offers robust mechanisms to gracefully manage unexpected situations in your code.

1. Potential Errors:

  • Runtime errors (e.g., accessing non-existent properties, division by zero).
  • Logic errors (e.g., incorrect calculations, invalid input).
  • Type errors (e.g., assigning incompatible data types).

2. Error Handling Techniques:

  • try-catch:
    • try block: Contains code that might potentially throw an error.
    • catch block: Catches the thrown error and provides an alternative execution path.
  • Syntax:

TypeScript

try {
  // Code that might throw an error
} catch (error) {
  // Code to handle the error (e.g., log the error, display a user-friendly message)
} finally {
  // Code that always executes, regardless of whether an error is thrown (optional)
}
  • throw statement: Explicitly throws an error object to signal an exceptional condition.

3. Example:

TypeScript

function calculateCircleArea(radius: number): number {
  if (radius <= 0) {
    throw new Error("Radius cannot be negative.");
  }
  return Math.PI * radius * radius;
}

try {
  let area = calculateCircleArea(-5); // This will throw an error
} catch (error) {
  console.error("Error:", error.message); // Handle the error gracefully
}

4. Custom Error Types:

  • Extending the built-in Error class: Create custom error types to provide more specific information about the error type and context.
  • Example:

TypeScript

class NegativeRadiusError extends Error {
  constructor(message: string) {
    super(message);
  }
}

function calculateCircleArea(radius: number): number {
  if (radius <= 0) {
    throw new NegativeRadiusError("Radius cannot be negative.");
  }
  return Math.PI * radius * radius;
}

5. Type Annotations for Errors:

  • Type annotations for thrown errors: Specify the type of error that a function might throw using the throws keyword.
  • Example:

TypeScript

function calculateCircleArea(radius: number): number throws NegativeRadiusError {
  // ... (implementation as before)
}

Effective error handling in TypeScript involves a combination of these techniques, enabling you to write robust and reliable applications that gracefully handle unexpected situations, enhancing the overall user experience.

Further Exploration:

The official TypeScript documentation provides detailed explanations of error handling mechanisms and best practices. Explore online resources and tutorials for more examples and advanced techniques to become proficient in handling errors in your TypeScript applications.