0% found this document useful (0 votes)
41 views20 pages

Exception Handling in JavaScript

Fuck yourself

Uploaded by

guru262004
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
41 views20 pages

Exception Handling in JavaScript

Fuck yourself

Uploaded by

guru262004
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 20

Exception Handling in JavaScript

An exception signifies the presence of an abnormal condition which requires special


operable techniques. In programming terms, an exception is the anomalous code
that breaks the normal flow of the code. Such exceptions require specialized
programming constructs for its execution.

What is Exception Handling


In programming, exception handling is a process or method used for handling the
abnormal statements in the code and executing them. It also enables to handle the
flow control of the code/program. For handling the code, various handlers are used
that process the exception and execute the code. For example, the Division of a
non-zero value with zero will result into infinity always, and it is an exception. Thus,
with the help of exception handling, it can be executed and handled.

In exception handling:

A throw statement is used to raise an exception. It means when an abnormal


condition occurs, an exception is thrown using throw.

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:

1. Syntax Error: When a user makes a mistake in the pre-defined syntax of a


programming language, a syntax error may appear.
2. Runtime Error: When an error occurs during the execution of the program,
such an error is known as Runtime error. The codes which create runtime
errors are known as Exceptions. Thus, exception handlers are used for
handling runtime errors.
3. Logical Error: An error which occurs when there is any logical mistake in the
program that may not produce the desired output, and may terminate
abnormally. Such an error is known as Logical error.
Error Object
When a runtime error occurs, it creates and throws an Error object. Such an object
can be used as a base for the user-defined exceptions too. An error object has two
properties:

1. name: This is an object property that sets or returns an error name.


2. message: This property returns an error message in the string form.

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().

Exception Handling Statements


There are following statements that handle if any exception occurs:

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.

Let's discuss each block of statement individually:

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.

The exception can be a string, number, object, or boolean value.

throw example with try…catch

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>

JavaScript Form Validation


HTML form validation can be done by JavaScript.

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;
}
}

The function can be called when the form is submitted:

HTML Form Example


<form name="myForm" action="/action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

JavaScript Can Validate Numeric Input


JavaScript is often used to validate numeric input:
Please input a number between 1 and 10

Submit

Not valid

Try it Yourself »

ADVERTISEMENT

Automatic HTML Form Validation


HTML form validation can be performed automatically by the browser:

If a form field (fname) is empty, the required attribute prevents this form
from being submitted:

HTML Form Example


<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

Automatic HTML form validation does not work in Internet Explorer 9 or


earlier.

Data Validation
Data validation is the process of ensuring that user input is clean, correct,
and useful.

Typical validation tasks are:

 has the user filled in all required fields?


 has the user entered a valid date?
 has the user entered text in a numeric field?

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.

Client side validation is performed by a web browser, before input is sent


to a web server.

HTML Constraint Validation


HTML5 introduced a new HTML validation concept called constraint
validation.

HTML constraint validation is based on:

 Constraint validation HTML Input Attributes


 Constraint validation CSS Pseudo Selectors
 Constraint validation DOM Properties and Methods

Constraint Validation HTML Input


Attributes
Attribute Description

disabled Specifies that the input element should be disabled

max Specifies the maximum value of an input element

min Specifies the minimum value of an input element


pattern Specifies the value pattern of an input element

required Specifies that the input field requires an element

type Specifies the type of an input element

For a full list, go to HTML Input Attributes.

Constraint Validation CSS Pseudo


Selectors
Selector Description

:disabled Selects input elements with the "disabled" attribute


specified

:invalid Selects input elements with invalid values

:optional Selects input elements with no "required" attribute specified

:required Selects input elements with the "required" attribute


specified

:valid Selects input elements with valid values


JavaScript Events Handling
The change in the state of an object is known as an Event. In html, there are various
events which represents that some activity is performed by the user or by the
browser. When javascript code is included in HTML, js react over these events and
allow the execution. This process of reacting over the events is called Event
Handling. Thus, js handles the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute the
task to be performed on the event.

Some of the HTML events and their event handlers are:

Mouse events:

Event Event Handler Description


Performed

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the
element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

Keyboard events:

Event Performed Event Handler Description


Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Form events:

Event Event Description


Performed Handler

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

change onchange When the user modifies or changes the value of a form
element

Window/Document events

Event Performed Event Handler Description

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

Let's discuss some examples over events and their handlers.

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

HTML document include JavaScript:: The JavaScript document is included in


our html page using the html tag. <src> tag is used to specify the source of external
JavaScript file. Following are some of the tasks that can be performed with
JavaScript:
 Performing html tasks
 Performing CSS tasks
 Handling events
 Validating inputs
Example 1: Example to understand how to use JavaScript in DHTML.
 HTML

<h1>

GeeksforGeeks

</h1>

<p id = "geeks">

Hello Geeks!

</p>

<script>
document.getElementById("geeks").innerHTML =

"A computer science portal for geeks";

</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"

style="display: flex; margin: auto; justify-content: center;">

GeeksforGeeks

</h1>

<input type = "Submit"

onclick = "Click()"

style="display: flex; margin: auto; justify-content: center;"/>


<script>

function Click() {

document.getElementById("para1").style.color = "green";

window.alert("Color changed to green");

</script>

Output:

Explanation: In this example, creating a function that will be invoked on click of a


button and it changes the color of text and display the alert on the screen. window
is an object of current window whose inbuilt method alert() is invoked in Click()
function.
Example 3: Validate input data using JavaScript.
 html

<style>

body {

margin-left: 50%;
}

h1 {

color: green;

</style>

<h1>

GeeksforGeeks

</h1>

<h4>

DHTML JavaScript

</h4>

<p>

Enter graduation percentage:

</p>

<input id="perc">

<button type="button" onclick="Validate()">

Submit

</button>

<p id="demo"></p>

<script>
function Validate() {

var x,text;

x=document.getElementById("perc").value;

if(isNaN(x)||x<60) {

window.alert("Not selected in GeeksforGeeks");

} else {

document.getElementById("demo").innerHTML=

"Selected: Welcome to GeeksforGeeks";

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.

You might also like