Error (exception) handling.(Microsoft Excel Office Scripts)

Japanese version.

This section describes how to handle errors (exceptions) using Office scripts.

Operations

Basic syntax

try {
  Processes for which you want to provide error handling.
} catch (error variable) {
  Processing to be performed when an error occurs.
}
finally{
  A process that is performed whether or not an error occurs.
}
function main(workbook: ExcelScript.Workbook) {

  try {
    // Processes for which you want to provide error handling.
    workbook.getWorksheet("Test").getRange("A-").setValue("try");

    // Line 5 is not executed due to an error.
    workbook.getWorksheet("Test").getRange("A1").setValue("try end");
  } catch (error) {
    // Processing to be performed when an error occurs.
    workbook.getWorksheet("Test").getRange("A2").setValue("Catch" + error.message);
  }
  finally {
    // A process that is performed whether or not an error occurs.
    workbook.getWorksheet("Test").getRange("A3").setValue("finally end");
  }
}

In the try block (the part enclosed by {}), describe the process to be performed to detect errors.
In the catch block, describe the process to be performed in case of an error.
In the finally block, describe the process to be performed whether or not an error occurs.
The try and catch blocks are required, but the finally block can be omitted.

Error handling in catch

Error Variables and Display

In catch, you can specify any name for the error variable.

If this error variable is used as an argument to console.log, the contents of the error will be displayed.

Throw exception

It is used infrequently, but after some processing, There are also cases where the same exception is raised further.
This is mainly the case when a function passes an exception to the caller.

For those who want to learn Office script effectively

The information on this site is now available in an easy-to-read e-book format.

Or Kindle Unlimited (unlimited reading).

You willl discover how to about basic operations.

By the end of this book, you will be equipped with the knowledge you need to use Excel Office Script to streamline your workflow.

Links

Office Scripts Articles