Core JavaScript

Error Handling

This program demonstrates the basics of exception handling and gives examples of the built-in errors.

ErrorHandling.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="ErrorHandling.js"></script>
</body>
</html>

ErrorHandling.js

// A simple example of a try-catch with the generic Error object
try {
	throw new Error("Something went wrong");
} catch (qError) {
	document.writeln("Error Name: " + qError.name + "<br />");
	document.writeln("Error Message: " + qError.message+ "<br /><hr />");
}

// A Simple example of a try-catch with a finally branch
try {
	throw new Error("Another error!");
} catch (qError) {
	document.writeln("Error Name: " + qError.name + "<br />");
	document.writeln("Error Message: " + qError.message+ "<br /><hr />");
} finally {
	document.writeln("Finally! Do something here to clean up resources. <br /><hr />");
}

// Standard types of errors
try {
	let i = 0;
	// Throw a range error
	i.toPrecision(1000);
} catch (qError) {
	document.writeln("Error Name: " + qError.name + "<br />");
	document.writeln("Error Message: " + qError.message+ "<br /><hr />");
}

try {
	// Throw a reference error
	let i = j;
} catch (qError) {
	document.writeln("Error Name: " + qError.name + "<br />");
	document.writeln("Error Message: " + qError.message+ "<br /><hr />");
}

try {
	// Throw a syntax error
	eval("alert('Hello World)");
} catch (qError) {
	document.writeln("Error Name: " + qError.name + "<br />");
	document.writeln("Error Message: " + qError.message+ "<br /><hr />");
}

try {
	let i = 0;
	// Throw a type error
	i.DoSomething();
} catch (qError) {
	document.writeln("Error Name: " + qError.name + "<br />");
	document.writeln("Error Message: " + qError.message+ "<br /><hr />");
}

try {
	// Throw a URI error
	decodeURI("%");
} catch (qError) {
	document.writeln("Error Name: " + qError.name + "<br />");
	document.writeln("Error Message: " + qError.message+ "<br /><hr />");
}
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.