Exception Handling in JavaScript
Exception Handling in JavaScript
In exception handling:
The thrown exception is handled by wrapping the code into the try…catch block. If an
error is present, the catch block will execute, else only the try block statements will
get executed.
Thus, in a programming language, there can be different types of errors which may
disturb the proper execution of the program.
Types of Errors
While coding, there can be three types of errors in the code:
Although Error is a generic constructor, there are following standard built-in error
types or error constructors beside it:
1. EvalError: It creates an instance for the error that occurred in the eval(), which
is a global function used for evaluating the js string code.
2. InternalError: It creates an instance when the js engine throws an internal
error.
3. RangeError: It creates an instance for the error that occurs when a numeric
variable or parameter is out of its valid range.
4. ReferenceError: It creates an instance for the error that occurs when an
invalid reference is de-referenced.
5. SyntaxError: An instance is created for the syntax error that may occur while
parsing the eval().
6. TypeError: When a variable is not a valid type, an instance is created for such
an error.
7. URIError: An instance is created for the error that occurs when invalid
parameters are passed in encodeURI() or decodeURI().
ADVERTISEMENT
o throw statements
o try…catch statements
o try…catch…finally statements.
JavaScript try…catch
A try…catch is a commonly used statement in various programming languages.
Basically, it is used to handle the error-prone part of the code. It initially tests the
code for all possible errors it may contain, then it implements actions to tackle those
errors (if occur). A good programming approach is to keep the complex code within
the try…catch statements.
try{} statement: Here, the code which needs possible error testing is kept within the
try block. In case any error occur, it passes to the catch{} block for taking suitable
actions and handle the error. Otherwise, it executes the code written within.
catch{} statement: This block handles the error of the code by executing the set of
statements written within the block. This block contains either the user-defined
exception handler or the built-in handler. This block executes only when any error-
prone code needs to be handled in the try block. Otherwise, the catch block is
skipped.
Note: catch {} statement executes only after the execution of the try {} statement.
Also, one try block can contain one or more catch blocks.
Syntax:
1. try{
2. expression; } //code to be written.
3. catch(error){
4. expression; } // code for handling the error.
try…catch example
1. <html>
2. <head> Exception Handling</br></head>
3. <body>
4. <script>
5. try{
6. var a= ["34","32","5","31","24","44","67"]; //a is an array
7. document.write(a); // displays elements of a
8. document.write(b); //b is undefined but still trying to fetch its value. Thus catch block will be i
nvoked
9. }catch(e){
10. alert("There is error which shows "+e.message); //Handling error
11. }
12. </script>
13. </body>
14. </html>
Throw Statement
Throw statements are used for throwing user-defined errors. User can define and
throw their own custom errors. When throw statement is executed, the statements
present after it will not execute. The control will directly pass to the catch block.
Syntax:
1. throw exception;
try…catch…throw syntax
1. try{
2. throw exception; // user can define their own exception
3. }
4. catch(error){
5. expression; } // code for handling exception.
1. <html>
2. <head>Exception Handling</head>
3. <body>
4. <script>
5. try {
6. throw new Error('This is the throw keyword'); //user-defined throw statement.
7. }
8. catch (e) {
9. document.write(e.message); // This will generate an error message
10. }
11. </script>
12. </body>
13. </html>
With the help of throw statement, users can create their own errors.
try…catch…finally statements
Finally is an optional block of statements which is executed after the execution of try
and catch statements. Finally block does not hold for the exception to be thrown.
Any exception is thrown or not, finally block code, if present, will definitely execute. It
does not care for the output too.
Syntax:
1. try{
2. expression;
3. }
4. catch(error){
5. expression;
6. }
7. finally{
8. expression; } //Executable code
try…catch…finally example
1. <html>
2. <head>Exception Handling</head>
3. <body>
4. <script>
5. try{
6. var a=2;
7. if(a==2)
8. document.write("ok");
9. }
10. catch(Error){
11. document.write("Error found"+e.message);
12. }
13. finally{
14. document.write("Value of a is 2 ");
15. }
16. </script>
17. </body>
18. </html>
If a form field (fname) is empty, this function alerts a message, and returns
false, to prevent the form from being submitted:
JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
Submit
Not valid
Try it Yourself »
ADVERTISEMENT
If a form field (fname) is empty, the required attribute prevents this form
from being submitted:
Data Validation
Data validation is the process of ensuring that user input is clean, correct,
and useful.
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many
different ways.
Server side validation is performed by a web server, after input has been
sent to the server.
For example, when a user clicks over the browser, add js code, which will execute the
task to be performed on the event.
Mouse events:
mouseover onmouseover When the cursor of the mouse comes over the
element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keyboard events:
Form events:
change onchange When the user modifies or changes the value of a form
element
Window/Document events
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the browser unload
resize onresize When the visitor resizes the window of the browser
Click Event
1. <html>
2. <head> Javascript Events </head>
3. <body>
4. <script language="Javascript" type="text/Javascript">
5. <!--
6. function clickevent()
7. {
8. document.write("This is JavaTpoint");
9. }
10. //-->
11. </script>
12. <form>
13. <input type="button" onclick="clickevent()" value="Who's this?"/>
14. </form>
15. </body>
16. </html>
Test it Now
MouseOver Event
1. <html>
2. <head>
3. <h1> Javascript Events </h1>
4. </head>
5. <body>
6. <script language="Javascript" type="text/Javascript">
7. <!--
8. function mouseoverevent()
9. {
10. alert("This is JavaTpoint");
11. }
12. //-->
13. </script>
14. <p onmouseover="mouseoverevent()"> Keep cursor over me</p>
15. </body>
16. </html>
Test it Now
Focus Event
1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onfocus="focusevent()"/>
6. <script>
7. <!--
8. function focusevent()
9. {
10. document.getElementById("input1").style.background=" aqua";
11. }
12. //-->
13. </script>
14. </body>
15. </html>
Test it Now
Keydown Event
1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onkeydown="keydownevent()"/>
6. <script>
7. <!--
8. function keydownevent()
9. {
10. document.getElementById("input1");
11. alert("Pressed a key");
12. }
13. //-->
14. </script>
15. </body>
16. </html>
Test it Now
Load event
1. <html>
2. <head>Javascript Events</head>
3. </br>
4. <body onload="window.alert('Page successfully loaded');">
5. <script>
6. <!--
7. document.write("The page is loaded successfully");
8. //-->
9. </script>
10. </body>
11. </html>
DHTML JavaScript
DHTML stands for Dynamic HTML. Dynamic means that the content of the web
page can be customized or changed according to user inputs i.e. a page that is
interactive with the user. In earlier times, HTML was used to create a static page. It
only defined the structure of the content that was displayed on the page. With the
help of CSS, we can beautify the HTML page by changing various properties like
text size, background color, etc. The HTML and CSS could manage to navigate
between static pages but couldn’t do anything else. If 1000 users view a page that
had their information for eg. Admit card then there was a problem because 1000
static pages for this application build to work. As the number of users increases,
the problem also increases, and at some point, it becomes impossible to handle this
problem. To overcome this problem, DHTML came into existence. DHTML
included JavaScript along with HTML and CSS to make the page dynamic. This
combo made the web pages dynamic and eliminated the problem of creating static
pages for each user. To integrate JavaScript into HTML, a Document Object
Model(DOM) is made for the HTML document. In DOM, the document is
represented as nodes and objects which are accessed by different languages like
JavaScript to manipulate the document.
DHTML JavaScript
<h1>
GeeksforGeeks
</h1>
<p id = "geeks">
Hello Geeks!
</p>
<script>
document.getElementById("geeks").innerHTML =
</script>
Output:
Explanation: In the above example, change the text of the paragraph using id. A
document is an object of HTML that is displayed in the current window or object
of DOM. The getElementById(id) gives the element id. The innerHTML defines
the content within the id element. The id attribute is used to change an HTML
document and its property. Paragraph content changed by document id. For
example document.getElementById(“geeks”).style.color = “blue”; It is used to set
the paragraph color using the id of elements.
Example 2: Creating an alert on click of a button.
HTML
<h1 id = "para1"
GeeksforGeeks
</h1>
onclick = "Click()"
function Click() {
document.getElementById("para1").style.color = "green";
</script>
Output:
<style>
body {
margin-left: 50%;
}
h1 {
color: green;
</style>
<h1>
GeeksforGeeks
</h1>
<h4>
DHTML JavaScript
</h4>
<p>
</p>
<input id="perc">
Submit
</button>
<p id="demo"></p>
<script>
function Validate() {
var x,text;
x=document.getElementById("perc").value;
if(isNaN(x)||x<60) {
} else {
document.getElementById("demo").innerHTML=
document.getElementById("demo").style.color="#009900";
</script>
Output:
Explanation: In this example, make a validate() function that ensures the user is
illegible or not. If the user enters > 60 then selected otherwise not selected.
Summer-time is here and so is the time to skill-up! More than 5,000 learners have
now completed their journey from basics of DSA to advanced level development
programs such as Full-Stack, Backend Development, Data Science.