Throwing Errors
In TypeScript, just like in any other programming language, errors are bound to occur. These errors can be due to many reasons such as wrong data entered by the user, failure of hardware, insufficient memory, etc. To deal with such errors, TypeScript provides a built-in mechanism called exceptions. Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our programs by transferring control to special functions called handlers.
To create an exception, you'll use the throw
statement. The throw
statement allows you to create a custom error. Technically, you can throw an exception (throw an error). Let's look at the basic syntax of the throw
statement:
throw expression;
The expression
can produce any value. The throw
statement then takes this value and "throws" it. When a value is thrown, execution of the current function stops and control returns to the calling function.
Here's an example of how to throw an Error:
function divide(dividend: number, divisor: number) {
if (divisor === 0) {
throw new Error("The divisor cannot be zero.");
}
return dividend / divisor;
}
try {
console.log(divide(10, 0));
} catch (e) {
console.log(e.message);
}
In the above code, we define a function divide
that takes two arguments: dividend
and divisor
. If the divisor
equals to 0, an Error is thrown with a message "The divisor cannot be zero." When we call this function in a try
block with 0 as the divisor, this Error is caught in the catch
block and the message is logged to the console.
Defining a Custom Error
You can also define your own error types in TypeScript. This is done by extending the base Error
class. Here's an example:
class DivideByZeroError extends Error {
constructor(message?: string) {
super(message);
this.name = "DivideByZeroError";
}
}
In the above code, we define a new error DivideByZeroError
that extends the base Error
class. This new error works just like the base Error
, but has a different name
.
You can use this custom error as follows:
function divide(dividend: number, divisor: number) {
if (divisor === 0) {
throw new DivideByZeroError("The divisor cannot be zero.");
}
return dividend / divisor;
}
try {
console.log(divide(10, 0));
} catch (e) {
if (e instanceof DivideByZeroError) {
console.log(e.message);
} else {
console.error(e);
}
}
In this code, when a DivideByZeroError
is thrown, it's caught in the catch
block and its message is logged to the console. For any other type of errors, they are logged as errors using console.error
.
Remember, error handling is a crucial part of TypeScript (or any language for that matter). Properly handling errors can save your program from crashing and provide meaningful error messages to your users. Therefore, understanding exceptions and how to handle them is a key skill for any TypeScript developer.