Definition :
It is an abnormal condition which terminates the program during its run time.
Types of exception handling :
Exception handlers are the keyboards which handles the exception during its runtime.
- Try
- Catch
- Finally
- Throw
Program :
<html>
<head>
<script language=”javascript”>
function display()
{
a=10;
b=0;
c=a/b;
document.write(c);
}
</script>
</head>
<body>
<input type=”button” value=”GetResult” onclick=”display()”/>
</body>
</html>
Try :
It is a block of code which is meant for monitoring the statements for exceptions. It transfers the control to the catch block whenever an exception has been encountered in the program.
Catch :
Catch is a block of code which is meant for handling the exceptions writtened by the try block. catch block will take one parameter that is a variable which holds the information about the exceptions occurred in the program. For one try block at least one catch are finally block needs to be there.
Program :
<html>
<head>
<script language=”javascript”>
function display()
{
try
{
a=10;
b=0;
c=a/d;
document.write(c);
}
catch(uuu)
{
alert(“invalid input”);
console.log(uuu);
console.error(uuu);
}
}
</script>
</head>
<body>
<input type=”button” value=”GetResult” onclick=”display()”/>
</body>
</html>
Finally :
Finally is the block of code which gets executed exactly once in the program life cycle.
Program :
<html>
<head>
<script language=”javascript”>
function display()
{
try
{
a=10;
b=2;
c=a/b;
document.write(c);
}
catch(err)
{
alert(“issue with application please try again”);
console.error(err);
}
finally {
alert(“END”);
}
}
</script>
</head>
<body>
<input type=”button” value=”Get Result” onclick=”display()”/>
</body>
</html>
Throw :
it is a keyword which is used for throwing the exceptions to the console based on the condition in exception handling.
Program :
<html>
<head>
<script language=”javascript”>
function display()
{
a=10;
b=2;
if(b==0)
throw “invalid denominator”;
c=a/b;
document.write(c);
}
</script>
</head>
<body>
<input type=”button” value=”Get Result” onclick=”display()”/>
</body>
</html>
Be First to Comment