JavaScript Errors

Error handling in JavaScript: try-catch, throw, and error types.

Try-Catch

try {                           # block of code to try
    undefinedFunction();
}
catch(err) {                    # block to handle errors
    console.log(err.message);
}

Throw Error

throw "My error message";    # throw a text

Input Validation

var x = document.getElementById("mynum").value;
try {
    if(x == "")  throw "empty";
    if(isNaN(x)) throw "not a number";
    x = Number(x);
    if(x > 10)   throw "too high";
}
catch(err) {
    document.write("Input is " + err);
    console.error(err);
}
finally {
    document.write("</br />Done");
}

Error Types

RangeError          # A number is "out of range"
ReferenceError      # An illegal reference has occurred
SyntaxError         # A syntax error has occurred
TypeError           # A type error has occurred
URIError            # An encodeURI() error has occurred