Share on Google+Share on Google+

JavaScript Exception Handling

Advertisement
JavaScript Exception Handling: Nowadays exception handling is one of the major part of programming, try..catch block is used for this purpose in JavaScript. In this tutorial you will get to know about try..catch block as well as throw statement

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

Advertisements

Advertisement

Posted on: November 7, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.