Typescript throw statement
Created By: chatGPT
In TypeScript, the
throw
statement is used to raise an exception. This allows a function to indicate that an unexpected condition has occurred. When an exception is thrown, the normal flow of control is interrupted. You can catch these exceptions using a try...catch
block. Here’s how you can use the throw
statement effectively in TypeScript:function validateInput(input: string): void {
if (input.trim() === '') {
throw new Error('Input cannot be empty.');
}
console.log('Valid input:', input);
}
To handle errors that are thrown, wrap your code in a
try
block, and add a catch
block to manage the error gracefully. This is crucial for maintaining a smooth user experience and preventing the application from crashing. Here's an example of this:try {
validateInput('');
} catch (error) {
console.error('An error occurred:', error.message);
}
You can also throw custom errors by creating a class that extends the built-in
Error
class. This approach gives more context for your errors. Here’s an example of how to implement a custom error class:class CustomError extends Error {
constructor(message: string) {
super(message);
this.name = 'CustomError';
}
}
function riskyFunction() {
throw new CustomError('Something went wrong!');
}
You can use the
throw
statement with any object, but it's a common practice to throw errors or instances of custom error classes. This helps to easily identify the source of the error and takes advantage of TypeScript's type checking. Remember to always handle thrown errors properly to ensure robust applications!try {
riskyFunction();
} catch (error) {
if (error instanceof CustomError) {
console.error('Caught a custom error:', error.message);
} else {
console.error('An unknown error occurred:', error);
}
}