throw Keyword in Typescript

Do you want to know about the throw keyword in Typescript? In this Typescript tutorial, I will explain how to use the throw keyword in Typescript with examples and code.

The throw keyword in TypeScript is used for error handling, allowing developers to throw exceptions when an error occurs. By using throw, you can create a custom error message or object, which can then be caught and handled with a try…catch block. This enhances error management in your TypeScript applications by providing clear, customizable error handling mechanisms.

What is the ‘throw’ Keyword in Typescript?

In TypeScript, as in JavaScript, the throw keyword is used to throw exceptions. When an error occurs, you can throw an exception, which can be an error message, an object, or anything that provides information about the error. The main purpose of “throw” is to signal that an error has occurred, allowing you to handle it appropriately.

How to use the Typescript throw keyword?

Now, let us see how to use the throw keyword in Typescript.

The syntax for the Typescript throw keyword is:

throw expression;

Here, expression is what you’re throwing. It can be a string, an error object, or any other value.

Here is an example.

function checkAge(age: number): void {
  if (age < 18) {
    throw new Error("Age must be at least 18");
  }
  console.log("Age is valid");
}

try {
  checkAge(15);
} catch (error) {
  console.error(error.message);
}

In this example, if age is less than 18, the function throws an error with a specific message. You can check the screenshot below.

throw Keyword in Typescript

Let us take another example.

TypeScript allows creating custom error classes. This is useful for creating specific types of errors for better error handling.

Here is the complete code:

class ValidationError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "ValidationError";
  }
}

function validateEmail(email: string): void {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    throw new ValidationError("Invalid email format");
  }
  console.log("Email is valid");
}

try {
  validateEmail("invalid-email");
} catch (error) {
  if (error instanceof ValidationError) {
    console.error(error.message);
  }
}

While it’s more common to throw Error objects, TypeScript allows throwing primitives like strings or numbers.

Here is a complete example:

function divide(a: number, b: number): number {
  if (b === 0) {
    throw "Division by zero error";
  }
  return a / b;
}

try {
  let result = divide(10, 0);
  console.log(result);
} catch (error) {
  console.error(error);
}

Conclusion

The throw keyword in TypeScript is used for error handling. By throwing errors, custom error types, or even primitives, you can create robust, error-resistant applications. Remember that thrown errors should be caught using try…catch blocks to handle them gracefully. With these examples, you should have a good understanding of how to use throw effectively in your TypeScript projects.

You may also like:

>