JavaScript Errors
Throw, and Try…Catch…Finally
The try
statement defines a code block to run (to try).
The catch
statement defines a code block to handle any error.
The finally
statement defines a code block to run regardless of the result.
The throw
statement defines a custom error.
Errors Will Happen!
When executing JavaScript code, different errors can occur.
Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things.
Example
In this example we misspelled “alert” as “adddlert” to deliberately produce an error:
<p id="demo"></p> <script> try { adddlert("Welcome guest!"); } catch(err) { document.getElementById("demo").innerHTML = err.message; } </script>
JavaScript catches adddlert as an error, and executes the catch code to handle it.
JavaScript try and catch
The try
statement allows you to define a block of code to be tested for errors while it is being executed.
The catch
statement allows you to define a block of code to be executed, if an error occurs in the try block.
The JavaScript statements try
and catch
come in pairs:
try { Block of code to try } catch(err) { Block of code to handle errors }
JavaScript Throws Errors
When an error occurs, JavaScript will normally stop and generate an error message.
The technical term for this is: JavaScript will throw an exception (throw an error).
JavaScript will actually create an Error object with two properties: name and message.
The throw Statement
The throw
statement allows you to create a custom error.
Technically you can throw an exception (throw an error).
The exception can be a JavaScript String
, a Number
, a Boolean
or an Object
:
throw "Too big"; // throw a text
throw 500; // throw a number
If you use throw
together with try
and catch
, you can control program flow and generate custom error messages.
Input Validation Example
This example examines input. If the value is wrong, an exception (err) is thrown.
The exception (err) is caught by the catch statement and a custom error message is displayed:
<!DOCTYPE html> <html> <body> <p>Please input a number between 5 and 10:</p> <input id="demo" type="text"> <button type="button" onclick="myFunction()">Test Input</button> <p id="p01"></p> <script> function myFunction() { const message = document.getElementById("p01"); message.innerHTML = ""; let x = document.getElementById("demo").value; try { if(x == "") throw "empty"; if(isNaN(x)) throw "not a number"; x = Number(x); if(x < 5) throw "too low"; if(x > 10) throw "too high"; } catch(err) { message.innerHTML = "Input is " + err; } } </script> </body> </html>
HTML Validation
The code above is just an example.
Modern browsers will often use a combination of JavaScript and built-in HTML validation, using predefined validation rules defined in HTML attributes:
<input id="demo" type="number" min="5" max="10" step="1">
You can read more about forms validation in a later chapter of this tutorial.
The finally Statement
The finally
statement lets you execute code, after try and catch, regardless of the result:
Syntax
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
Example
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Error: " + err + ".";
}
finally {
document.getElementById("demo").value = "";
}
}
The Error Object
JavaScript has a built in error object that provides error information when an error occurs.
The error object provides two useful properties: name and message.
Error Object Properties
Property | Description |
---|---|
name | Sets or returns an error name |
message | Sets or returns an error message (a string) |
Error Name Values
Six different values can be returned by the error name property:
Error Name | Description |
---|---|
EvalError | An error has occurred in the eval() function |
RangeError | A number “out of range” has occurred |
ReferenceError | An illegal reference has occurred |
SyntaxError | A syntax error has occurred |
TypeError | A type error has occurred |
URIError | An error in encodeURI() has occurred |
The six different values are described below.
Eval Error
An EvalError
indicates an error in the eval() function.
Newer versions of JavaScript do not throw EvalError. Use SyntaxError instead.
Range Error
A RangeError
is thrown if you use a number that is outside the range of legal values.
For example: You cannot set the number of significant digits of a number to 500.
Example
let num = 1;
try {
num.toPrecision(500); // A number cannot have 500 significant digits
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
Reference Error
A ReferenceError
is thrown if you use (reference) a variable that has not been declared:
Example
let x = 5;
try {
x = y + 1; // y cannot be used (referenced)
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
Syntax Error
A SyntaxError
is thrown if you try to evaluate code with a syntax error.
Example
try {
eval("alert('Hello)"); // Missing ' will produce an error
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
Type Error
A TypeError
is thrown if you use a value that is outside the range of expected types:
Example
let num = 1;
try {
num.toUpperCase(); // You cannot convert a number to upper case
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
URI (Uniform Resource Identifier) Error
A URIError
is thrown if you use illegal characters in a URI function:
Example
try {
decodeURI("%%%"); // You cannot URI decode percent signs
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
Non-Standard Error Object Properties
Mozilla and Microsoft defines some non-standard error object properties:
fileName (Mozilla)
lineNumber (Mozilla)
columnNumber (Mozilla)
stack (Mozilla)
description (Microsoft)
number (Microsoft)
Do not use these properties in public web sites. They will not work in all browsers.
levaquin us purchase levaquin
oral dutasteride buy ondansetron 4mg online zofran 8mg price
aldactone 25mg pill cost propecia 5mg diflucan 200mg cost
cheap ampicillin 250mg erythromycin 500mg us erythromycin brand
buy sildenafil 100mg online cheap robaxin 500mg usa robaxin 500mg without prescription
cheap suhagra cheap suhagra 100mg estrace price
order lamictal order minipress 2mg generic buy tretinoin gel
purchase tadalis for sale avanafil 200mg generic diclofenac 100mg oral
purchase isotretinoin pill zithromax 250mg usa zithromax 500mg cheap
order indomethacin 50mg generic terbinafine 250mg canada order generic trimox
buy tadalafil 10mg pill Buy cheap viagra now viagra pill
arimidex 1 mg ca 50mg viagra sildenafil over the counter
tadalafil 40mg pas cher cialis 20mg pour homme sildenafil 25mg comprimГ©
deltasone 40mg us 2.5 cialis buy viagra 100mg
cialis 20mg kaufen für männer viagra 50mg kaufen für männer sildenafil 50mg generika rezeptfrei kaufen
isotretinoin over the counter cheap accutane 40mg stromectol tablets
cheap modafinil acetazolamide sale order diamox 250mg generic
doxycycline 100mg canada order vardenafil sale lasix 40mg uk
ramipril 5mg generic order temovate generic buy astelin 10ml generic
oral catapres 0.1 mg tiotropium bromide canada spiriva 9mcg sale
buspar 10mg without prescription buy phenytoin 100mg online cheap buy oxybutynin online cheap
buy terazosin 1mg without prescription generic arava buy sulfasalazine 500 mg pill
alendronate pills order pepcid 20mg online cheap buy famotidine 20mg without prescription
buy olmesartan 20mg without prescription order olmesartan pills cost diamox 250mg
tacrolimus 5mg without prescription tacrolimus 5mg pills order ursodiol 150mg generic
buy imdur 20mg sale order azathioprine pills order telmisartan 80mg for sale
buy bupropion 150mg online cheap purchase strattera online cheap order seroquel without prescription
molnunat 200 mg for sale molnupiravir over the counter order lansoprazole generic
buy zoloft 50mg pills order lexapro buy sildenafil 100mg sale
imuran order online female viagra pill buy sildenafil 100mg generic
real cialis pharmacy prescription pfizer viagra 100mg price buy generic viagra 50mg
revia generic buy albendazole 400 mg pills purchase aripiprazole online cheap
order avlosulfon 100mg pill allegra 180mg without prescription perindopril for sale online
order provera 5mg online buy generic microzide buy cyproheptadine for sale
buy generic provigil 100mg approved canadian pharmacy ivermectin online
fluvoxamine 50mg pill cost nizoral purchase glucotrol sale
order accutane online cheap buy amoxicillin 250mg pill buy prednisone pills
piracetam online order order piracetam sildenafil next day delivery usa
buy azithromycin 500mg for sale azithromycin 500mg oral buy generic neurontin 100mg
purchase cialis online cheap cialis otc sildenafil 50mg pills
order furosemide without prescription order doxycycline for sale buy plaquenil 200mg generic
order cialis 40mg online order generic tadalafil 5mg anafranil 50mg for sale
chloroquine 250mg cost buy cenforce generic oral baricitinib
canadian pharmacy generic levitra https://canadianpharmacy.icu/# canadian pharmacy generic levitra
canadian neighbor pharmacy fda approved pharmacies in canada
https://indiapharmacy.store/# buying generic drugs from india
prescription drugs without doctor approval pain meds online without doctor prescription
dating seiten in schweiz single friends dating
https://datingonline1st.com/# best free online dating sites
find free dating site browse free dating without registering
https://datingonline1st.shop/# dating online sites
local singles in my area top single service
top rated dating websites flirt singles
datingnow life mature interracial dating
https://datingonline1st.com/# a free dating site
connecting singles online members flirt dating site
https://datingonline1st.com/# best adult site
f dating site online date
matchmeetups dating site my dating sites
over the counter medicine for acid reflux over the counter antihistamine
cvs over the counter asthma inhaler antibiotic eye drops over the counter
male to female hormones over the counter best over the counter teeth whitening
https://drugsoverthecounter.shop/# silvadene cream over the counter
over the counter migraine medicine over the counter ear wax removal
https://drugsoverthecounter.com/# zofran over the counter
mupirocin ointment over the counter nausea medicine over the counter for pregnancy
strongest diuretic over the counter potassium supplements over-the-counter
over the counter insulin mupirocin ointment over the counter
https://drugsoverthecounter.com/# over the counter erection pills
potassium supplements over-the-counter over the counter birth control
best sleeping pills over the counter over the counter yeast infection treatment
over the counter nausea medicine sleep aids over the counter
over the counter pills like viagra muscle relaxer over the counter
over the counter diet pills that work over the counter medication for uti
https://drugsoverthecounter.com/# over the counter viagra
potassium supplements over-the-counter is ivermectin over the counter
over the counter essentials epinephrine over the counter
uti medicine over the counter over the counter flu medicine
over the counter essentials login united healthcare over the counter essentials
nausea medicine over the counter for pregnancy over the counter acne treatments
https://over-the-counter-drug.com/# over the counter muscle relaxers cvs
amoxicillin over the counter over the counter diuretic
over the counter steroid cream econazole nitrate cream over the counter
omeprazole over the counter uti treatment over the counter
https://over-the-counter-drug.com/# over the counter sleep aid
uti treatment over the counter over the counter blood thinners
over-the-counter over the counter medicine for strep throat
over the counter laxatives blood pressure over the counter medication
antibiotic eye drops over the counter best over the counter weight loss pills
over the counter medicine for strep throat over the counter inhalers
For instance, Tavazoie et al overnight cialis delivery 0 Fasting insulin ОјIU ml 0 29 11
amoxicillin buy no prescription generic amoxil online
https://doxycycline.science/# buy doxycycline online
generic zithromax zithromax price canada
doxy doxycycline 100 mg or buy doxycycline for dogs
http://ja-alaska.org/__media__/js/netsoltrademark.php?d=over-the-counter-drug.com doxycycline hyclate
doxycycline order online doxycycline 100mg and how to buy doxycycline online doxycycline online
can you buy zithromax over the counter in mexico zithromax
https://doxycycline.science/# doxycycline hyclate
zithromax zithromax price south africa
https://amoxil.science/# cost of amoxicillin prescription
generic stromectol minocycline 100
amoxicillin 500mg for sale uk order amoxil
https://doxycycline.science/# doxycycline 200 mg
stromectol pills stromectol generic name
https://doxycycline.science/# doxycycline tetracycline
ivermectin 3 mg dose buy stromectol
https://stromectol.science/# minocycline 50 mg without doctor
zithromax for sale where can i buy zithromax uk
doxycycline 50mg buy doxycycline for dogs or where to get doxycycline
http://go-funds.ca/__media__/js/netsoltrademark.php?d=doxycycline.science doxycycline hyc 100mg
vibramycin 100 mg buy doxycycline online and doxycycline hydrochloride 100mg buy doxycycline 100mg
minocycline 50mg tablets where can i buy stromectol or dynacin minocycline
http://ianfalconer.org/__media__/js/netsoltrademark.php?d=stromectol.science stromectol 3 mg price
generic ivermectin for humans stromectol 3mg and ivermectin new zealand minocycline rash
https://amoxil.science/# can i buy amoxicillin over the counter in australia
buy zithromax online zithromax for sale 500 mg
price of doxycycline doxycycline monohydrate or doxycycline order online
http://plasticsurgerycolumbusoh.com/__media__/js/netsoltrademark.php?d=doxycycline.science doxycycline 100mg dogs
buy doxycycline without prescription uk doxycycline tablets and order doxycycline buy doxycycline without prescription uk
zithromax online usa no prescription buy zithromax online
https://stromectol.science/# minocycline 100mg
buy stromectol price of stromectol
https://stromectol.science/# minocycline 100 mg tabs
amoxicillin tablet 500mg buy amoxicillin online no prescription or amoxicillin without prescription
http://fluidcapital.com/__media__/js/netsoltrademark.php?d=amoxil.science buy amoxicillin online with paypal
amoxicillin 800 mg price generic amoxicillin cost and how much is amoxicillin prescription amoxicillin 500mg capsules
https://doxycycline.science/# 200 mg doxycycline
vibramycin 100 mg doxycycline hyc 100mg
amoxicillin for sale ampicillin amoxicillin
https://zithromax.science/# zithromax online paypal
buy zithromax zithromax 250 mg tablet price
minocycline for sinus infection stromectol ireland or stromectol liquid
http://rlrt.info/__media__/js/netsoltrademark.php?d=stromectol.science ivermectin price uk
buy minocycline 100 mg otc ivermectin malaria and stromectol online minocycline foam
doxycycline 100mg tablets doxycycline order online or cheap doxycycline online
http://ifuckinghatetheacademyofartcollege.biz/__media__/js/netsoltrademark.php?d=doxycycline.science where to get doxycycline
doxylin doxycycline order online and doxycycline 200 mg doxycycline hyc 100mg
cialis from india He will show speed in the Classic
Everything what you want to know about pills. earch our drug database.
buy ivermectin
Read here. Definitive journal of drugs and therapeutics.
Learn about the side effects, dosages, and interactions. Read information now.
stromectol 3mg cost
Everything about medicine. What side effects can this medication cause?
Learn about the side effects, dosages, and interactions. Everything what you want to know about pills.
ivermectin lotion for lice
safe and effective drugs are available. Some trends of drugs.
Comprehensive side effect and adverse reaction information. Read here.
https://stromectolst.com/# stromectol 6 mg dosage
Everything what you want to know about pills. Drugs information sheet.
buy ivermectin pills stromectol pill or order minocycline 100 mg online
http://urathletics.net/__media__/js/netsoltrademark.php?d=stromectol.science buy minocycline 100mg otc
ivermectin 0.1 uk ivermectin online and ivermectin lice minocycline 100mg tabs
Cautions. Actual trends of drug.
stromectol coronavirus
Commonly Used Drugs Charts. Cautions.