TypeScript custom Error Handling example
TypeScript Error Handling : Exercise-2 with Solution
Write a TypeScript function that calls a non-existent function. Use a try-catch block to catch the resulting error and display a custom error message.
Sample Solution:
TypeScript Code:
function callNonExistentFunction(): void {
try {
// Attempt to call a non-existent function
nonExistentFunction();
} catch (error) {
console.error("Custom Error: The function does not exist.");
}
}
// Call the function
callNonExistentFunction();
Explanations:
In the exercise above -
- The "callNonExistentFunction()" function tries to call a non-existent function nonExistentFunction().
- Inside the try block, the code attempts to call the non-existent function, which will result in a runtime error.
- If an error occurs, the catch block catches the error, and a custom error message is displayed using console.error.
Output:
"Custom Error: The function does not exist."
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Exception Handling example
Next: TypeScript integer parsing with Error Handling.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join