JavaScript Error Handling: Exercises, Practice, Solutions
JavaScript Error Handling: [ 13 exercises with solution]
[An editor is available at the bottom of the page to write and execute the scripts. Go to the editor]
1. Throw Error for Non-Integer
Write a JavaScript function that takes a number as a parameter and throws a custom 'Error' if the number is not an integer.
2. Handle TypeError in Try-Catch
Write a JavaScript program that uses a try-catch block to catch and handle a 'TypeError' when accessing a property of an undefined object.
3. Throw Error for Division by Zero
Write a JavaScript function that accepts two numbers as parameters and throws a custom 'Error' if the second number is zero.
4. Throw Error for Negative Number
Write a JavaScript function that takes a number as a parameter and throws a custom 'Error' if the number is negative.
5. Throw Error for Empty Array
Write a JavaScript function that takes an array as a parameter and throws a custom 'Error' if the array is empty.
6. Throw Error for Empty String
Write a JavaScript function that takes a string as a parameter and throws a custom 'Error' if the string is empty.
7. Handle RangeError for Invalid Index
Write a JavaScript program that uses a try-catch block to catch and handle a 'RangeError' when accessing an array with an invalid index.
8. Multiple Catch Blocks
Write a JavaScript program that shows the use of multiple catch blocks to handle different types of errors separately.
9. 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.
10. Try-Catch-Finally Example
Write a JavaScript program that demonstrates the use of the 'try-catch-finally' statement to catch and handle an error, and then execute some cleanup code in the 'finally' block.
11. Handle EvalError
Write a JavaScript program that uses a try-catch block to catch and handle an 'EvalError' when evaluating an invalid expression.
12. Handle ReferenceError
Write a JavaScript program that uses a try-catch block to catch and handle a 'ReferenceError' when accessing an undefined variable.
13. Handle SyntaxError for JSON Parsing
Write a JavaScript program that uses a try-catch block to catch and handle a 'SyntaxError' when parsing an invalid JSON string.
More to Come !
* To run the code mouse over on Result panel and click on 'RERUN' button.*
Live Demo:
See the Pen javascript-common-editor by w3resource (@w3resource) on CodePen.
Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics