Have you ever built an automation tool in Google Apps Script (GAS), clicked run thinking “This is perfect!”, only to be stopped dead in your tracks by a bright red error message on screen?
For instance, if someone secretly renames a Google Sheets tab or a required cell is left blank, your script can panic and immediately terminate before finishing its job.
During a harsh winter here in Sapporo, when regular JR trains or buses get suspended due to heavy snowstorms, having an alternate subway route planned out gives you total peace of mind. Programming works the exact same way!
Building an intentional backup plan into your code that says, “If an error happens, handle it this way,” is the exact mechanism we’ll explore today: try...catch.
In this guide, we’ll thoroughly cover how try...catch works to dramatically boost the reliability of your Google Apps Script projects—from foundational syntax and practical real-world workflows to common rookie pitfalls you should avoid!
1. What Exactly Is try…catch?
In a nutshell, try...catch is an insurance policy (error handling) that prevents your program from abruptly crashing when an error strikes, guiding it safely through an alternative route.
Think of It as a Everyday Backup Plan!
In our daily lives, we naturally practice “error handling” without even realizing it:
- Without a backup plan (No try…catch):
- “You head out to a famous soup curry restaurant in Sapporo, but discover it’s temporarily closed! In shock, all your plans for the day get ruined, and you just go straight home…”
- With a backup plan (With try…catch):
- try: “Head to your top-choice soup curry spot first.”
- catch (Handling when an issue occurs): “If it turns out to be closed (an error!), pivot to that delicious roux curry shop nearby and enjoy lunch anyway!”
That is precisely how try...catch operates in programming. Instead of breaking down entirely the moment an error occurs, your code detects the problem and can display a helpful message or trigger fallback actions safely.
What Happens If You Don’t Use try…catch?
Imagine a script designed to execute multiple steps in order: (1) Read spreadsheet data ➡ (2) Perform calculations ➡ (3) Send notifications via chat or email.
Without try...catch, if an unexpected error occurs during step (1), your script will terminate immediately on the spot. Steps (2) and (3) will never execute, and your end user will be left staring at an intimidating red error box with zero clue as to what went wrong.
However, when you wrap your operations in try...catch, any error in step (1) gets smoothly intercepted. You can inform the user gracefully with a dialog box like “Sheet not found” and exit safely without a crash.
2. Mastering Basic Syntax and Structure
The fundamental syntax of try...catch is very straightforward. It consists of up to three blocks:
try {
// 1. Code that might throw an error (Main Route)
} catch (e) {
// 2. Code executed only when an error occurs (Fallback Route)
} finally {
// 3. Code that ALWAYS executes at the end, error or not (Optional)
}
Breaking Down Each Role
tryblock- Inside the
{ }braces, write the primary logic you wish to execute. - If everything runs cleanly with no errors, the execution exits the
tryblock normally (thecatchblock is completely skipped).
- Inside the
catch (e)block- The exact moment an error is thrown inside the
tryblock, execution jumps straight into these braces. - The
e(Error Object) inside the parentheses automatically receives metadata regarding what went wrong.
- The exact moment an error is thrown inside the
finallyblock (Optional)- Use this whenever there is cleanup logic that must run once at the end, regardless of whether an error was thrown or not (you can omit this block if it isn’t needed).
3. STEP 1: Experience an Unhandled Error Situation
First, let’s intentionally write code that throws an error to see how GAS behaves when try...catch is missing.
1. Prepare the Spreadsheet
- Open a practice Google Spreadsheet and name the sheet tab “Sapporo Office”.
- From the top menu, go to Extensions > Apps Script.
2. Run Intentionally Broken Code
The following script attempts to retrieve a non-existent sheet named “Otaru Office”:
function testErrorWithoutTryCatch() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Attempting to fetch a non-existent sheet (sheet variable becomes null)
var sheet = ss.getSheetByName("Otaru Office");
// Attempting to call getRange() on null triggers an error right here!
var value = sheet.getRange("A1").getValue();
Logger.log("A1 cell value: " + value);
}
When you execute this, GAS abruptly halts and displays a harsh red error in the console:
TypeError: Cannot read properties of null (reading 'getRange')
If a non-technical coworker encounters this while using your tool, they’ll inevitably panic and worry that the entire system has broken.
4. STEP 2: Catch Errors Safely with try…catch in Practice
Now, let’s wrap that problematic code inside a try...catch statement to handle errors gracefully!
1. Paste the Code
Copy and paste the following snippet into your script editor:
function testErrorWithTryCatch() {
try {
// 1. Get active spreadsheet (see Lesson 2)
var ss = SpreadsheetApp.getActiveSpreadsheet();
// 2. Get sheet by name (specifying a non-existent sheet)
var sheet = ss.getSheetByName("Otaru Office");
// 3. Extract data (This throws an error because sheet does not exist!)
var value = sheet.getRange("A1").getValue();
// If an error occurs, this line is skipped and execution jumps to catch
Logger.log("Retrieved value: " + value);
} catch (e) {
// 4. Code executed when an error occurs
Logger.log("[Error Detected] An issue occurred during execution.");
Logger.log("Error details: " + e.message);
// 5. Display a friendly alert dialog to the user (see Lesson 26)
SpreadsheetApp.getUi().alert(
"Error Notification",
"The 'Otaru Office' sheet was not found.\nPlease verify that the sheet name is correct.",
SpreadsheetApp.getUi().ButtonSet.OK
);
}
}
2. Check Execution Results
Run this function and observe what happens:
- Instead of stopping dead with a fatal red crash, your custom informative message appears in the execution log:Plaintext
Info [Error Detected] An issue occurred during execution. Info Error details: Cannot read properties of null (reading 'getRange') - A friendly alert popup appears over the Google Spreadsheet informing the user: “The ‘Otaru Office’ sheet was not found. Please verify that the sheet name is correct.”
Rather than breaking entirely, the script clearly explained why the process failed and finished safely without leaving the user stranded!
5. STEP 3: Ensuring Cleanup with the finally Block
You can optionally append a finally block to your try...catch statement.
Code written inside finally always executes at the very end—regardless of whether the try block succeeded smoothly or the catch block handled an error.
Practical Example: Always Recording Execution Logs
For instance, when tracking start and end timestamps in a separate log sheet, you’ll want that completion timestamp written even if something failed midway through.
function processWithFinally() {
Logger.log("--- Starting process ---");
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// Some processing...
var data = sheet.getRange("A1").getValue();
Logger.log("Data retrieved: " + data);
} catch (e) {
Logger.log("Caught an error: " + e.message);
} finally {
// Always executes at the end, whether errors happened or not!
Logger.log("--- All process steps completed (cleanup finished) ---");
}
}
The log inside finally will execute under any condition. This is exceptionally helpful for cleanup tasks, such as releasing lock resources, unsetting temporary flags, or closing external connections.
6. 3 Essential Real-World Use Cases for try…catch
Here are three classic automation scenarios where try...catch proves invaluable in day-to-day office scripting:
1. Handling External Integrations (API Calls & Email Dispatch)
Tasks involving network communication—such as GmailApp.sendEmail() (Lesson 31) or external Web APIs (Lesson 72)—are prone to intermittent failures due to network timeouts or server downtime.
try {
// Send email via Gmail
GmailApp.sendEmail("example@example.com", "Business Trip Report", "Here is the body text.");
} catch (e) {
// Log failure and notify a backup administrator address
Logger.log("Failed to send email: " + e.message);
}
2. Preventing Single-Row Failures from Halting Batch Loops
When looping through 100 expense report records (see Lesson 7 on appendRow), it would be frustrating if one corrupted row stopped the entire 100-item batch midway through.
for (var i = 0; i < dataList.length; i++) {
try {
// Process row one by one
processRowData(dataList[i]);
} catch (e) {
// Log error for the faulty row and continue loop for the next rows!
Logger.log("Error processing row " + (i + 1) + ": " + e.message);
}
}
By placing try...catch inside the loop, you can build a resilient script that skips bad data records and safely finishes the remaining 99 items!
3. Validating Empty Cells or Non-Numeric Strings in Calculations
When fetching values with getValue() (Lesson 5), error handling prevents formulas from crashing your script with NaN if an end-user accidentally inputs letters or leaves required cells empty.
7. The 3 Major Pitfalls Beginners Encounter (and Solutions)
While try...catch is powerful, misunderstandings can lead to sneaky bugs. Keep these three points in mind:
Trap 1: Syntax Errors (SyntaxError) Cannot Be Caught!
try...catch can only intercept errors that happen while the code is actively executing (runtime exceptions).
Syntax errors—such as missing closing brackets, forgotten semicolons, or typos in keywords—are detected by the script engine before compilation and execution. Therefore, try...catch cannot catch them.
- ✕ Uncatchable example (Syntax Error):JavaScript
try { var ss = SpreadsheetApp.getActiveSpreadsheet( // Missing closing parenthesis! } catch (e) { ... }
Always verify syntax highlighting and red underlines in your Apps Script editor before running!
Trap 2: Silently Swallowing Errors
The worst habit to avoid is leaving your catch block empty.
// ✕ Bad practice example!
try {
var value = sheet.getRange("A1").getValue();
} catch (e) {
// Empty block! Nobody will ever know an error happened!
}
Doing this creates a “silent error.” No message will show and nothing gets written to your logs, leading to agonizing debugging sessions where code simply fails to work for mysterious reasons.
Always make it a rule to at least log what happened using Logger.log(e.message) or e.stack inside your catch block!
Trap 3: Knowing the Difference Between e and e.message
The parameter e in catch (e) represents the full Error object:
Logger.log(e)➡ Prints the full error object representationLogger.log(e.message)➡ Outputs a clean, concise text description (such as “Cannot read properties of null…”)Logger.log(e.stack)➡ Outputs the stack trace, showing exact line numbers where the failure originated
Using e.message for friendly user alerts and e.stack for internal troubleshooting makes your development life so much smoother!
8. Summary & What’s Next
In this lesson, we explored how to make your Google Apps Script projects bulletproof using try...catch error handling.
Key Takeaways
- Write your main logic in
try, and place safe fallback/recovery logic incatch - Using
try...catchprevents sudden script crashes and allows friendly user dialog notifications - The
finallyblock ensures critical cleanup logic runs every time, with or without errors - Never leave
catchempty—always log the incident withLogger.log(e.message)
With that, you have officially completed Phase 3: “Automation, Custom UI & Error Handling (Lessons 21–30)”! Fantastic job!
From managing spreadsheet ranges to custom menus (Lesson 25), dialog popups (Lesson 26), and now error handling, you are well on your way to writing professional, resilient automation tools.
Coming Up: Moving into Gmail Integration & Automated Emailing!
In our next tutorial (Lesson 31), we enter Phase 4: “Gmail Integration & Automated Email Dispatch (Lessons 31–40)”!
We’ll discover how to orchestrate Gmail directly from GAS, transforming spreadsheet records into beautifully formatted emails sent on complete autopilot. Stay tuned!
