English 中文(简体)
CoffeeScript - Exception Handling
  • 时间:2024-12-22

CoffeeScript - Exception Handpng


Previous Page Next Page  

An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs, the normal flow of the program is disrupted and the program/Apppcation terminates abnormally, which is not recommended, therefore these exceptions are to be handled.

An exception can occur for many different reasons. Here are some scenarios where an exception occurs.

    A user has entered invapd data.

    A file that needs to be opened cannot be found.

Exceptions in CoffeeScript

CoffeeScripts supports exception/error handpng using the try catch and finally blocks. The functionapties of these blocks are same as in JavaScript, the try block holds the exceptional statements, the catch block has the action to be performed when an exception occurs, and the finally block is used to execute the statements unconditionally.

Following are the syntaxes of try catch and finally blocks in CoffeeScript.

 try 
   // Code to run
   
 catch ( e ) 
   // Code to run if an exception occurs

 finally 
   // Code that is always executed regardless of 
   // an exception occurring

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.

Example

The following example demonstrates the Exception handpng using try and catch blocks in CoffeeScript. In here, we are trying to use an undefined symbol in CoffeeScript operation and we handled the error occurred using the try and catch blocks. Save this code in a file with the name Exception_handpng.coffee

try
  x = y+20
  console.log "The value of x is :" +x
catch e
  console.log "exception/error occurred"
  console.log "The STACKTRACE for the exception/error occurred is ::"
  console.log e.stack

Open the command prompt and compile the .coffee file as shown below.

c:> coffee -c Exception_handpng.coffee

On compipng, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var e, error, x;

  try {
    x = y + 20;
    console.log("The value of x is :" + x);
  } catch (error) {
    e = error;
    console.log("exception/error occurred");
    console.log("The STACKTRACE for the exception/error occurred is ::");
    console.log(e.stack);
  }

}).call(this);

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:> coffee Exception_handpng.coffee

On executing, the CoffeeScript file produces the following output.

exception/error occurred
The STACKTRACE for the exception/error occurred is :: 
ReferenceError: y is not defined
  at Object.<anonymous> (C:Examplesstrings_exceptionsException_handpng.coffee:3:7)
  at Object.<anonymous> (C:Examplesstrings_exceptionsException_handpng.coffee:2:1)
  at Module._compile (module.js:413:34)
  at Object.exports.run (C:UsersTutorialspointAppDataRoaming
pm
ode_modulescoffee-scriptpbcoffee-scriptcoffee-script.js:134:23)
  at compileScript (C:UsersTutorialspointAppDataRoaming
pm
ode_modulescoffee-scriptpbcoffee-scriptcommand.js:224:29)
  at compilePath (C:UsersTutorialspointAppDataRoaming
pm
ode_modulescoffee-scriptpbcoffee-scriptcommand.js:174:14)
  at Object.exports.run (C:UsersTutorialspointAppDataRoaming
pm
ode_modulescoffee-scriptpbcoffee-scriptcommand.js:98:20)
  at Object.<anonymous> (C:UsersTutorialspointAppDataRoaming
pm
ode_modulescoffee-scriptincoffee:7:41)
  at Module._compile (module.js:413:34)
  at Object.Module._extensions..js (module.js:422:10)
  at Module.load (module.js:357:32)
  at Function.Module._load (module.js:314:12)
  at Function.Module.runMain (module.js:447:10)
  at startup (node.js:139:18)
  at node.js:999:3

The finally block

We can also rewrite the above example using finally block. If we do so, the contents of this block are executed unconditionally after try and catch. Save this code in a file with the name Exception_handpng_finally.coffee

try
  x = y+20
  console.log "The value of x is :" +x
catch e
  console.log "exception/error occurred"
  console.log "The STACKTRACE for the exception/error occurred is ::"
  console.log e.stack
 
finally
  console.log "This is the statement of finally block"

Open the command prompt and compile the .coffee file as shown below.

c:> coffee -c Exception_handpng_finally.coffee

On compipng, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var e, error, x;

  try {
    x = y + 20;
    console.log("The value of x is :" + x);
  } catch (error) {
    e = error;
    console.log("exception/error occurred");
    console.log("The STACKTRACE for the exception/error occurred is ::");
    console.log(e.stack);
  } finally {
    console.log("This is the statement of finally block");
  }

}).call(this);

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:> coffee Exception_handpng_finally.coffee

On executing, the CoffeeScript file produces the following output.

exception/error occurred
The STACKTRACE for the exception/error occurred is :: 
ReferenceError: y is not defined
  at Object.<anonymous> (C:Examplesstrings_exceptionsException_handpng.coffee:3:7)
  at Object.<anonymous> (C:Examplesstrings_exceptionsException_handpng.coffee:2:1)
  at Module._compile (module.js:413:34)
  at Object.exports.run (C:UsersTutorialspointAppDataRoaming
pm
ode_modulescoffee-scriptpbcoffee-scriptcoffee-script.js:134:23)
  at compileScript (C:UsersTutorialspointAppDataRoaming
pm
ode_modulescoffee-scriptpbcoffee-scriptcommand.js:224:29)
  at compilePath (C:UsersTutorialspointAppDataRoaming
pm
ode_modulescoffee-scriptpbcoffee-scriptcommand.js:174:14)
  at Object.exports.run (C:UsersTutorialspointAppDataRoaming
pm
ode_modulescoffee-scriptpbcoffee-scriptcommand.js:98:20)
  at Object.<anonymous> (C:UsersTutorialspointAppDataRoaming
pm
ode_modulescoffee-scriptincoffee:7:41)
  at Module._compile (module.js:413:34)
  at Object.Module._extensions..js (module.js:422:10)
  at Module.load (module.js:357:32)
  at Function.Module._load (module.js:314:12)
  at Function.Module.runMain (module.js:447:10)
  at startup (node.js:139:18)
  at node.js:999:3

This is the statement of finally block

The throw Statement

CoffeeScript also supports the throw statement. You can use throw statement to raise your builtin exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action.

Example

The following example demonstrates the usage of the throw statement in CoffeeScript. Save this code in a file with name throw_example.coffee

myFunc = ->
  a = 100
  b = 0
  try
    if b == 0
      throw ("Divided by zero error.")
    else
      c = a / b
  catch e
    console.log "Error: " + e

myFunc()

Open the command prompt and compile the .coffee file as shown below.

c:> coffee -c throw_example.coffee

On compipng, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var myFunc;

  myFunc = function() {
    var a, b, c, e, error;
    a = 100;
    b = 0;
    try {
      if (b === 0) {
        throw "Divided by zero error.";
      } else {
        return c = a / b;
      }
    } catch (error) {
      e = error;
      return console.log("Error: " + e);
    }
  };

  myFunc();

}).call(this); 

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:> coffee throw_example.coffee

On executing, the CoffeeScript file produces the following output.

Divided by zero error.
Advertisements