JavaScript is a loosely-typed language. It does not give compile-time errors. So some times you will get a runtime error for accessing an undefined variable or calling undefined function etc.
note: try catch block does not handle syntax errors.
JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#.
In the above example, we are calling function Sum, which is not defined yet. So, try block will throw an error which will be handled by catch block. Ex includes error message that can be displayed.
The finally block executes regardless of whatever happens.
Example of finally block:
try
{
var result = Sum(20, 20); // Sum is not defined yet
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML = ex;
}
finally{
document.getElementById("message").innerHTML = "finally block executed";
}
Use throw keyword to raise a custom error.
Example of throw error
try
{
throw "Error occurred";
}
catch(ex)
{
alert(ex);
}