11. Error Handling
Error handling is an essential part of writing robust and reliable code in TypeScript. In this article, we’ll explore how to use try
-catch
blocks for error handling and create custom exception types to represent specific error scenarios in your TypeScript applications.
try
-catch
in TypeScript
The try
-catch
statement in TypeScript is used to catch and handle exceptions that may occur during the execution of code. It allows you to gracefully handle errors without crashing the entire program.
Here’s the basic syntax of a try
-catch
block:
try {
// Code that may throw an exception
} catch (error) {
// Handle the exception
}
- The
try
block contains the code that might throw an exception. - If an exception is thrown within the
try
block, control is transferred to thecatch
block. - The
catch
block receives the error object, which you can use to inspect and handle the error.
Example:
function divide(a: number, b: number): number {
if (b === 0) {
throw new Error("Division by zero is not allowed.");
}
return a / b;
}
try {
const result = divide(10, 0);
console.log("Result:", result);
} catch (error) {
console.error("Error:", error.message);
}
In this example, the divide
function throws an error if the divisor b
is zero. The try
-catch
block handles this error and prevents the program from crashing.
Custom Exception Types
While TypeScript provides built-in error types like Error
, you can create custom exception types to represent specific error scenarios in your application. Custom exception types are typically classes that extend the Error
class or any other base error type.
Example:
class CustomError extends Error {
constructor(message: string) {
super(message);
this.name = "CustomError";
}
}
function processInput(input: string): string {
if (!input) {
throw new CustomError("Input is required.");
}
return `Processed: ${input}`;
}
try {
const result = processInput("");
console.log(result);
} catch (error) {
if (error instanceof CustomError) {
console.error("Custom Error:", error.message);
} else {
console.error("Unexpected Error:", error.message);
}
}
In this example, the CustomError
class extends Error
and is used to represent custom error scenarios. When throwing and catching errors, you can use the instanceof
operator to identify and handle specific error types.
Creating custom exception types allows you to provide more meaningful error messages and differentiate between various error scenarios in your code.
Conclusion
Error handling is a crucial aspect of writing reliable TypeScript applications. The try
-catch
statement provides a structured way to handle exceptions and prevent unexpected crashes. Additionally, custom exception types allow you to represent specific error scenarios with descriptive error messages. By implementing error handling and using custom exception types effectively, you can improve the robustness and maintainability of your TypeScript code.