HTML and CSS Reference
In-Depth Information
Another part to the
try…catch
block is the
finally.
block. This block is added directly after
the
catch
block. The significance of the
finally.
block is that the code inside it runs all the time.
This isn't to say that the code in the
finally.
block can't have its own errors resulting in excep-
tions, but whether or not the code in the
try
block has an error, the code in the
finally.
block
still runs. Consider the following code:
function WorkthroughArray() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "blue";
contxt.arc(50, 50, 25, 0, 360);
context.fill();
context.strokeStyle = "red";
context.stroke();
}
This function contains an intentional spelling error, contxt, which results in an exception.
Nothing after the line that causes the exception runs. However, placing a
try…catch…finally
block around this code provides more control over the flow:
try{
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "blue";
contxt.arc(50, 50, 25, 0, 360);
context.fill();
context.strokeStyle = "red";
context.stroke();
}
catch (e) {
console.log(e.message);
}
finally {
//do any final logic before exiting the method
}
Now, with the structured error handling in place, when the line with the typo is hit,
processing jumps into the
catch
block. In this block, the error could be logged for future
diagnostics. After the
catch
block completes, the
finally.
block runs. If any cleanup or variable
resetting needs to be done, it can be done here even though an exception occurs. The
finally.
block also runs. If the typo is fixed so that no exceptions occur in the
try
block, the
catch
doesn't occur because of nothing to catch, but the
finally.
block still runs. The
finally.
block
always runs as the last part of a
try…catch…finally
block.
Variable scope applies to each block within the
try…catch
block. If a variable is declared
within the
try
portion, it won't be accessible from the catch of the
finally.
. If you want to have
Search WWH ::
Custom Search