w3resource

TypeScript Exception Handling example

TypeScript Error Handling : Exercise-1 with Solution

Write a TypeScript function that throws an exception when a specified condition is not met. Implement a try-catch block to handle the exception and display an error message.

Sample Solution:

TypeScript Code:

function checkCondition(value: number): void {
  if (value < 0) {
    throw new Error("Condition not satisfied: Value must be non-negative.");
  }
}

try {
  const inputValue = -34; // Change this value to test the condition
  checkCondition(inputValue);
  console.log("Condition is met.");
} catch (error: any) { // Specify the type of 'error' as 'any' or a more specific type
  console.error(`Error: ${error.message}`);
}

Explanations:

In the exercise above -

  • First, the "checkCondition()" function takes a value as a parameter and checks if it's less than 0. If the condition is not met (value is negative), it throws an exception with a custom error message.
  • In the 'try' block, we call the "checkCondition()" function with an input value. You can change the 'inputValue' to test different conditions.
  • If the condition is met (value is non-negative), the code proceeds to the console.log statement.
  • If the condition is not met, the 'catch' block catches the error, and we display an error message using console.error.

Output:

"Error: Condition not satisfied: Value must be non-negative."

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript Error Handling Exercises Home
Next: TypeScript custom Error Handling example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.