JavaScript Exception Handling:
Try...catch block help to handle the exception handling, try..catch block works together. You use the catch statement to define a block of code that will execute if an exception to the normal running of the code occurs in the block of code defined by the try statement. Exception means a circumstance that is extraordinary and unpredictable. If you compare with an error, which is something in the code that has been written incorrectly. If no exception occurs, the code inside the catch statement will never execute.
JavaScript Exception Handling Example 1:
<html>
<head>
<script type="text/javascript">
try
{
promptu("This is wrong text");
}
catch (err)
{
document.write(err.description);
}
</script>
</head>
</html>
Output:
Object expected
Example 2:
<html>
<head>
<script type="text/javascript">
x=-31;
try
{
if(x<0)
throw "ErN";
if(x==0)
throw "ErO";
if(x>0)
throw "ErP";
}
catch (err)
{
if(err=="ErN")
document.write("Negative number");
if(err=="ErO")
document.write("Zero");
if(err=="ErP")
document.write("Positive number");
}
</script>
</head>
</html>
Output:
Negative number
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.