JavaScript Exception Handling


 

JavaScript Exception Handling

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: 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

Ads