JavaScript
HTML
CSS
jQuery
PHP
SQL
WordPress
JavaScript Reference

Quick Reference

The try…catch…finally statement handles errors without stopping JavaScript to output the error.

The try statement defines the code block to run, while the catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result.

				
					<!-- html element to place output -->
<p id="my_output"></p>
				
			

In the following, we use x as our value (let’s say it was input by the user in a form field). The user was asked to input a number between 1 and 5.

We then use the throw statement to look for errors (try) and output them (catch) to the html element.

If no errors are found, nothing will be output using the “catch”, and the code will continue to run after line 13.

				
					// variable
let x = 13;

// try catch finnally statement
try { 
	if(x == '')  throw 'You did not enter a value.';
    if(isNaN(x)) throw 'You did not enter a number.';
    if(x > 5)   throw 'The number entered is too high.';
    if(x < 1)  throw 'The number entered is too low.';
  }
catch(error) {
  	document.getElementById('my_output').innerHTML = error;
  }
finally {
  	alert('Don\'t forget to visit our tutorials!');
  }
				
			

Output

				
					The number entered is too high.

Don't forget to visit our tutorials! (alert)
				
			

Syntax

				
					try {
    tryCode - code to be executed
}
catch(err) {
    catchCode - code to handle errors
}
finally {
    finallyCode - code to be executed regardless of the try result
}
				
			

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.

JavaScript
HTML
CSS
jQuery
PHP
SQL
WordPress

Why 1SMARTchicken?

This site was built and is maintained to benefit my autistic son.
See More →

My Son's Name is Johnny

He was diagnosed as autistic quite late, at age four...
His story

Buy Me a Coffee

Thanks for your support!

Feedback

If you see an error on the page or the code itself is incorrect or incomplete, or just plain wrong, please let us know. We’re always learning. NOTE: we do not sell your information and will not send you spam emails.