---
title: "How to apply try-catch block on exception area in JS?"  
description: "How to apply try-catch block on exception area in JS?"  
author: "Ravi Vishwakarma"  
published: 2021-07-19  
canonical: https://answers.mindstick.com/qa/93744/how-to-apply-try-catch-block-on-exception-area-in-js  
category: "web application"  
tags: ["javascript", "web application development", "web development"]  
reading_time: 7 minutes  

---

# How to apply try-catch block on exception area in JS?

How to [apply](https://www.mindstick.com/articles/13148/discover-to-apply-make-up-like-a-professional-supermodel) try-[catch block](https://www.mindstick.com/forum/159348/how-does-an-exception-find-the-correct-catch-block) on [exception](https://www.mindstick.com/articles/61/exception-handling-in-c-sharp) area in JS?

## Answers

### Answer by user

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. Runtime errors, also called exceptions, occur during execution (after compilation/interpretation). For example, the following line causes a runtime error because here the syntax is correct, but at runtime, it is trying to call a method that does not exist.

```
<script type = 'text/javascript'>
   <!--
      window.printme();
   //-->
</script>
```

The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...[catch](https://www.mindstick.com/interview/34391/explain-the-python-try-except-catch)...finally construct as well as the throw operator to handle exceptions. You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.

1. The try statement lets you test a [block](https://www.mindstick.com/interview/34449/difference-between-object-block-and-file-storage) of code for errors.
2. The catch statement lets you handle the error.
3. The throw statement lets you create custom errors.
4. The finally statement lets you execute code, after try and catch, regardless of the result.

**Syntax.**

```
<script type = 'text/javascript'>
   <!--
      try {
         // Code to run
         [break;]
      }
      catch ( e ) {
         // Code to run if an exception occurs
         [break;]
      }
      [ finally {
         // Code that is always executed regardless of
         // an exception occurring
      }]
   //-->
</script>
```

The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch.

```
<!DOCTYPE html>
<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title></title>
</head>
<body>
       <p>Click the following to see the result:</p>
       <form>
           <input type='number' id='val1' placeholder='Enter first value '/>
           <input type='number' id='val2' placeholder='Enter second value '/>
           <input type='button' value='Check Me' onclick='myFunc();' />
       </form>
    <p id='res'></p>
    <script type='text/javascript'>
        function myFunc() {
            var a = document.getElementById('val1').value;
            var b = document.getElementById('val2').value;
            try {
                if (b == 0) {
                    throw ('Doesn't divide by zero');
                } else {
                    var c = a / b;
                    document.getElementById('res').innerHTML='Result is : '+c;
                }
            }
            catch (e) {
                alert('Error: ' + e);
                document.getElementById('res').innerHTML = e;
            }
        }
    </script>
   </body>
</html>
```

\

### Answer by Ethan Karla

Abnormal condition is called execption. In JavaScript, an exception is an event that disrupts the execution of the program. It is an object which is throw at time of program execution. Exception Handling is a mechanism to handle runtime errors such divide by zero, invalid input, bad activity on web pages, etc. Exception handling is to maintain the normal flow of the application at runtime.

**There are some key words are use in exception .**

1. **try** statement is used to test block of code
2. **catch** statement is used to catch the error
3. We use the throw keyword to **throw** the exception which is caught by the catch statement.
4. We use **finally** block to show a message. The finally block is executed each time whether try or catch block is executed or not.

```
Syntax.
<script type = 'text/javascript'>
   <!--
      try {
         // Code to run        // throw exception message         [break;]
      }
      catch ( e ) {
         // Code to run if an exception occurs
         [break;]
      }
      [ finally {
         // Code that is always executed regardless of
         // an exception occurring
      }]
   //-->
</script>
```

Example \

```
<!doctype html>
<html lang='en'>
  <head>
    <!-- Required meta tags -->
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>
    <!-- Bootstrap CSS -->
    <link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css' integrity='sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T' crossorigin='anonymous'>
    <title>Execption handling</title>
  </head>
  <body>
    <div class='container mt-5'>
        <h1 class='text-center'>Exception Handling</h1>
       <form >
           <div class='form-group'>
               <input type='number' class='form-control' id='val1' placeholder='Enter first value '/>
           </div>
           <div class='form-group'>
               <input type='number' class='form-control' id='val2' placeholder='Enter second value '/>
           </div>
           <div class='form-group'>
               <input type='button' id='btn' class='btn btn-primary'  value='Check Me' onclick='myFunc()' />
           </div>
       </form>
    <p id='res' class=''></p>
    <script type='text/javascript'>
        function myFunc() {
            var a = document.getElementById('val1').value;
            var b = document.getElementById('val2').value;
            var btn = document.getElementById('btn');
            try {
                if (a.length == 0 ) {
                    throw ('Please enter first value !!!');
                } else if (b.length == 0) {
                    throw ('Please enter second value !!!');
                } else if (b == 0) {
                    throw ('Doesn't divide by zero');
                } else {
                    var c = a / b;
                    document.getElementById('res').innerHTML = 'Success : ' + c;
                    document.getElementById('res').className = 'alert alert-success';
                    btn.className = 'btn btn-primary';
                }
            }
            catch (e) {
                document.getElementById('res').innerHTML = e;
                btn.className = 'btn btn-danger';
                document.getElementById('res').className = 'alert alert-danger';
            }
        }
    </script>
    </div>
    <script src='https://code.jquery.com/jquery-3.3.1.slim.min.js' integrity='sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo' crossorigin='anonymous'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js' integrity='sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1' crossorigin='anonymous'></script>
    <script src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js' integrity='sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM' crossorigin='anonymous'></script>
  </body>
</html>
```

Output.

![How to apply try-catch block on exception area in JS?](https://answers.mindstick.com/questionanswer/97908f03-b88c-40f2-a9a1-4e81a7526b6f/images/a42da786-bb10-44ff-b90a-0ad9f7f4816e.png)

![How to apply try-catch block on exception area in JS?](https://answers.mindstick.com/questionanswer/97908f03-b88c-40f2-a9a1-4e81a7526b6f/images/7b1dcf37-30ec-418b-9d1c-38bdece902e1.png)

![How to apply try-catch block on exception area in JS?](https://answers.mindstick.com/questionanswer/97908f03-b88c-40f2-a9a1-4e81a7526b6f/images/1b6f620f-4775-41e8-a0da-54b4f0237362.png)

\

\


---

Original Source: https://answers.mindstick.com/qa/93744/how-to-apply-try-catch-block-on-exception-area-in-js

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
