TypeScript integer parsing with Error Handling
TypeScript Error Handling : Exercise-3 with Solution
Write a TypeScript function that parses an integer from a string. Handle potential exceptions caused by invalid input using try-catch.
Sample Solution:
TypeScript Code:
function parseIntegerFromString(input: string): number | null {
try {
// Attempt to parse the integer from the input string
const parsedInt = parseInt(input, 10);
// Check if the parsing result is NaN (not a number)
if (isNaN(parsedInt)) {
throw new Error("Invalid input: Not a valid integer.");
}
return parsedInt;
} catch (error: any) { // Specify the type of 'error' as 'any' or a more specific type
// Handle the error and return null to indicate failure
console.error(`Error: ${error.message}`);
return null;
}
}
// Test the function with valid and invalid input
const validInput = "100";
const invalidInput = "TypeScript";
const parsedValid = parseIntegerFromString(validInput);
if (parsedValid !== null) {
console.log(`Parsed Integer (Valid Input): ${parsedValid}`);
} else {
console.log("Parsing failed for valid input.");
}
const parsedInvalid = parseIntegerFromString(invalidInput);
if (parsedInvalid !== null) {
console.log(`Parsed Integer (Invalid Input): ${parsedInvalid}`);
} else {
console.log("Parsing failed for invalid input.");
}
Explanations:
In the exercise above -
- The "parseIntegerFromString()" function attempts to parse an integer from the input string using parseInt.
- Inside the try block, it checks if the parsing result is NaN (not a number) and throws an error if the input is invalid.
- If an error occurs, the catch block catches the error, displays an error message, and returns null to indicate a parsing failure.
- Finally, we test the function with both valid and invalid input strings and display the parsed integers or failure messages accordingly.
Output:
"Parsed Integer (Valid Input): 100" "Error: Invalid input: Not a valid integer." "Parsing failed for invalid input."
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript custom Error Handling example.
Next: TypeScript file Handling with Error Catching.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics