Google Apps Script Exception Handling


Errors In Computer Programming

There are three types of common errors in programming:
  • Syntax Errors
  • Runtime Errors
  • Logical Errors

i) Syntax Errors

Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and at interpret time in Google Apps Script.

For example, the following line causes a syntax error because we used Variable name V caps.

function errorTest(){
Var num1=100;
}

Try to Save ( Ctrl+S )

Error log: Missing ; before statement. (line 47, file "RegEx")

When a syntax error occurs in Google Apps Script, IDE don't allow to save the last changes.

ii) Runtime Errors

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 function that does not exist.

function errorTest2(){
var test=method();
Logger.log(test);
}

O/p: ReferenceError: "method" is not defined. (line 7, file "Errors")
f
You can able to save the code file, it will show error only when you call the particular function.

(iii) Logical Errors.

Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected.

You cannot catch those errors, because it depends on your business requirement/logic what type of logic you want to put in your program.

The try...catch...finally Statement

In Google Apps Script implements the try...catch...finally construct as well as the throw operator to handle exceptions.

You can catch programmer-generated and runtime exceptions, but you cannot catch Google Apps Script syntax errors.

Here is the try...catch...finally block 

Syntax

try {
    Block of code to try;
}
catch(err) {
    Block of code to handle errors;
finally {
    Block of code to be executed regardless of the try / catch result;
}


Try Catch Finally Example

function tryCatch1(){
  try {
    var num2=100;
    var result=num1/num2;
    Logger.log("Expected result"+result);
  }
  catch(err) {
    Logger.log(err);
  } 
  finally {
    Logger.log("You are in finally block!");
  }
}

//[18-04-01 13:52:34:695 IST] ReferenceError: "num1" is not defined.
//[18-04-01 13:52:34:695 IST] You are in finally block!


I would suggest, use try...catch statement for each function. It will helps to monitor error in your project online/offline.




Comments

Popular posts from this blog

Google Apps Script Regular Expressions

Responsive Web Apps using Google Apps Script