w3resource

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. Write a JavaScript function that takes a number as a parameter and throws a custom 'Error' if the number is not an integer.

Click me to see the solution

2. Write a JavaScript program that uses a try-catch block to catch and handle a 'TypeError' when accessing a property of an undefined object.

Click me to see the solution

3. Write a JavaScript function that accepts two numbers as parameters and throws a custom 'Error' if the second number is zero.

Click me to see the solution

4. Write a JavaScript function that takes a number as a parameter and throws a custom 'Error' if the number is negative.

Click me to see the solution

5. Write a JavaScript function that takes an array as a parameter and throws a custom 'Error' if the array is empty.

Click me to see the solution

6. Write a JavaScript function that takes a string as a parameter and throws a custom 'Error' if the string is empty.

Click me to see the solution

7. Write a JavaScript program that uses a try-catch block to catch and handle a 'RangeError' when accessing an array with an invalid index.

Click me to see the solution

8. Write a JavaScript program that shows the use of multiple catch blocks to handle different types of errors separately.

Click me to see the solution

9. Write a JavaScript program that uses a try-catch block to catch and handle a 'URIError' when decoding an invalid URI.

Click me to see the solution

10. 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.

Click me to see the solution

11. Write a JavaScript program that uses a try-catch block to catch and handle an 'EvalError' when evaluating an invalid expression.

Click me to see the solution

12. Write a JavaScript program that uses a try-catch block to catch and handle a 'ReferenceError' when accessing an undefined variable.

Click me to see the solution

13. Write a JavaScript program that uses a try-catch block to catch and handle a 'SyntaxError' when parsing an invalid JSON string.

Click me to see the solution

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/javascript-exercises/error-handling/index.php