How to apply try-catch block on exception area in JS?

Asked 19-Jul-2021
Viewed 239 times

1 Answer


1

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?

How to apply try-catch block on exception area in JS?

How to apply try-catch block on exception area in JS?