HTML and CSS Reference
In-Depth Information
Because the WorkWithCanvas method has no exception handling, the exception bubbles
up to the calling method, the next method in the stack. This continues through the stack until
either an exception handler is met or the browser receives the exception and treats it as an
unhandled exception. Of course, in this case, the variables in the WorkWithCanvas method
can't be accessed, so if anything needed to be done in a finally block, the try…catch…finally
block should be either moved into the WorkWithCanvas method, or the WorkWithCanvas
method can handle the error and rethrow it for further processing.
The concept of raising an error is also known as throwing an exception . Custom objects and
libraries throw exceptions as needed to the consumers of the libraries. The objects or libraries
expect you to meet certain conditions and if those conditions aren't met, they can throw
an exception for the consumer to deal with. To continue with the example, the exception is
handled in the WorkWithCanvas method and then rethrown. An exception is thrown using
the throw keyword:
function WorkWithCanvas() {
try {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
contxt.arc(50, 50, 25, 0, 360);
context.fillStyle = "blue";
context.strokeStyle = "red";
} catch (e) {
//handle the exception as appropriate
throw e;
} finally {
In this example, the exception can be handled in the catch block as needed, and then
thrown back up the call stack to be handled again at another level.
More commonly when working with custom libraries, you can create custom exceptions to
give users information specific to the situation that occurred:
var ball = {
x: -1,
y: -1,
draw: function DrawBall(c) {
if (this.x < 0)
throw new Error(25, "Invalid X coordinate");
window.onload = function () {
try {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
} catch (e) {
Search WWH ::

Custom Search