errorHandling.pptx
errorHandling.pptx
• Handling Exceptions
• The onError event handler
• A method associated with the window object.
• It is called whenever an exception occurs
• The try … catch … finally block
• Similar to Java try … catch … finally block
• For handling exceptions in a code segment
• Use throw statement to throw an exception
• You can throw value of any type
• The Error object
• Default object for representing an exception
• Each Error object has a name and message properties
How to
<html>
use “onError” event handler?
<head>
<title>onerror event handler example</title>
<script type="text/javascript">
function errorHandler(){
alert("Error Ourred!");
}
// JavaScript is casesensitive
// Don't write onerror!
window.onError = errorHandler;
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello there;
</script>
</body>
</html>
try … catch … finally
try {
// Contains normal codes that might throw an exception.
} catch ( errorVariable ) {
// Codes here get executed if an exception is thrown
// in the try block.
} finally {
// Executed after the catch or try block finish
} catch( errVar ) {
document.write("Exception caught<br>");
// errVar is an Error object
// All Error objects have a name and message properties
document.write("Error name: " + errVar.name + "<br>");
document.write("Error message: " + errVar.message +
"<br>");
} finally {
document.write("Finally block reached!");
}
</script>
Throwing Exception
<script type="text/javascript">
try{
var num = prompt("Enter a number (1-2):", "1");
// You can throw exception of any type
if (num == "1")
throw "Some Error Message";
else
if (num == "2")
throw 123;
else
throw new Error ("Invalid input");
} catch( err ) {
alert(typeof(errMsg) + "\n" + err);
// instanceof operator checks if err is an Error object
if (err instanceof Error)
alert("Error Message: " + err.message);
}
</script>