Skip to content

Diagnostic reference

Cannot retrieve the next object: iterator has reached the end

Fix Exception: Cannot retrieve the next object: iterator has reached the end in Apps Script by checking hasNext() before calling next() on DriveApp iterators.

Updated December 6, 2026

Apps Script error

Exception: Cannot retrieve the next object: iterator has reached the end.

What it means

DriveApp.getFilesByName(), getFoldersByName(), searchFiles(), and folder.getFiles() return a FileIterator or FolderIterator rather than an array. Calling .next() when zero items match, or after the last item was already consumed, throws an exception instead of returning null.

Related error messages

  • Exception: Cannot retrieve the next object: iterator has reached the end. (DriveApp.getFoldersByName)
  • Exception: Cannot retrieve the next object: iterator has reached the end. (DriveApp.searchFiles)

Before and after

The code before and after the fix.

Problem 2 changed lines
function getTemplateFile() {
  // Throws when no file named "Invoice Template" exists in Drive.
  return DriveApp.getFilesByName('Invoice Template').next();
}
Fixed 5 changed lines
function getTemplateFile() {
  const files = DriveApp.getFilesByName('Invoice Template');
  if (!files.hasNext()) {
    throw new Error('No Drive file named "Invoice Template" was found.');
  }
  return files.next();
}

How to fix it

  • Store the iterator in a variable and check if (files.hasNext()) before calling files.next().
  • To process every match, loop with while (files.hasNext()) { const file = files.next(); ... }.
  • If you expected a match, check exact spelling, account ownership, and whether the file is in the trash.

Things to check

  • Drive allows multiple files with the same name. When you need one specific file reliably, open it with DriveApp.getFileById(id) instead of searching by name.
  • myFunction catches DriveApp iterator next() calls without a hasNext() guard statically under rule MF95005 and offers a quick fix.

In the Apps Script editor

Catch errors like this before clicking Run.

myFunction (published as Error Checker for Google Apps Script on the Chrome Web Store) checks your code while you edit at script.google.com. Diagnostics, autocomplete, and rule-based quick fixes are free without an account, run in your browser, and request no Google Drive, Gmail, or Apps Script project OAuth scopes. Writing Apps Script with an AI coding agent? Connect the Apps Script MCP server to run the same static checks before pasting code.