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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/typescript-exercises/typescript-error-handling-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics