JavaScript Program: Handling URIError with Try-Catch block for invalid URI decoding
JavaScript Error Handling: Exercise-9 with Solution
Handle URIError for Invalid URI
Write a JavaScript program that uses a try-catch block to catch and handle a `URIError` when decoding an invalid URI.
Sample Solution:
JavaScript Code:
Output:
"Decoded URI:" "https://example.com/" "URIError:" "URI malformed"
Note: Executed on JS Bin
Explanation:
In the above exercise -
- The "decodeURIString()" function attempts to decode the provided URIString using the decodeURI function within a try block.
- If the URI is valid, the decoding process will succeed, and the decoded URI will be logged to the console.
- However, if the URI is invalid, a URIError will be thrown. We catch this error in the catch block and check if the error is an instance of URIError using the instanceof operator.
- If it is a URIError, we log a message with the prefix 'URIError:' followed by the error message. Otherwise, for other types of error, we log a message with the prefix 'Error:' followed by the error message.
Next we call the “decodeURIString()” function twice. The first call with a valid URI 'https://example.com/' will decode successfully and print the decoded URI to the console.
The second call with an invalid URI 'https://example.com/%%invalidURI' will throw a URIError due to invalid characters. The catch block will handle this error and print a message indicating the URIError.
Flowchart:
Live Demo:
Improve this sample solution and post your code through Disqus.
Error Handling Exercises Previous: Handling different types of errors with multiple catch blocks.
Error Handling Exercises Next: Error handling and cleanup with the try-catch-finally statement.
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