Javascript - Javascript try catch
Temmuz 5, 2012 by Javascript Tutorial
|
|
his Javascript tutorial contains and tries to cover following subjects:
- Explanation of Javascript try catch
- Example to Javascript try catch
Articles tries to provide answer to following questions and issues:
- How to handle errors in Javascript
- How to create a try catch block in javascript?
- How to display a friendly message when an error occurs in javascript code?
Articles pre-requisites following information:
- General knowledge of variables in Javascript
- General knowledge of functions
- General knowledge of HTML
Explanation of Javascript try catch
In this Javascript Tutorial, we will cover Javascript try catch subject to understand how to create a javascript try catch block to handle errors, display custom messages or HTML pages when an error is detected in run-time of javascript application life cycle.
Why we need to handle an error? Lets cover that subject before stepping into handling errors. Errors are something that may happen due programmer did not expect, or had not opportunity to know the case while code is compiled. For instance, lets assume that we have a javascript function in our javascript code that accepts number as parameter with getting input from a textbox. However, user did not enter number, or similar cases. To provide handling that type of errors, javascript provides a feature "try catch".
Javascript try catch is two block with each block containing a code block to be executed. When we have a code block that is candidate to produce error to be handled, for example a code block that accepts input from user interaction, this block is placed within try block. "try" block means, any error in its block will trigger "catch" block. "Catch" block contains a parameter between parenthesis following it, and this variable stores error details. Similar to other languages, that variable is called "exception" object.
To be practical, lets inspect syntax of javascript try catch first.
try
{
execute some code...
}
catch(errorObject)
{
execute some code...
}
In above syntax, if a code within try block contains error, or causes error in run-time, catch block is triggered and executes code inside it. If no error happens, code within "try" block is executed.
Lets use a javascript try catch in an example.
Example to Javascript try catch
In following javascript example, we will create a Javascript try catch block and execute and we will make a syntax error in "try" block. Due syntax error, our page will show code from catch block.
HTML page shows result at the right pane. We created a javascript try catch, and with aware of doing it, we made a syntax mistake in "try" block. That triggered "catch" block and code within "catch" has been executed.
Data Layers
Area: | programming \ languages \ javascript \ \ \ |
Ref: | |
Loc: | articles |
Tags: | javascript |
|