vimtricks.wiki Concise Vim tricks, one at a time.

How do I handle errors gracefully in Vimscript using try-catch blocks?

Answer

:try / :catch / :endtry

Explanation

Vimscript has a structured exception handling system using :try, :catch, :finally, and :endtry. This lets you run risky commands — such as searching for a pattern or calling a function that might not exist — without propagating errors to the user.

How it works

  • :try opens the guarded block
  • :catch /{pattern}/ intercepts exceptions whose message matches the regex
  • v:exception holds the exception string inside a :catch block
  • :finally runs unconditionally (useful for cleanup)
  • :endtry closes the block
  • :throw 'message' raises a custom exception

Example

Silently attempt a substitution that may not find a match:

try
  substitute/old/new/ge
catch /E486/
  " E486: Pattern not found — silently ignore
endtry

Or wrap a function call that might fail:

function! SafeFormat() abort
  try
    call SomeFormatterThatMightFail()
  catch
    echomsg 'Formatter error: ' . v:exception
  endtry
endfunction

Tips

  • :catch with no argument catches all exceptions
  • Vim's built-in errors follow the pattern E{number}: catch /E\d\+/ to catch any Vim error
  • v:throwpoint gives the script location where the exception was raised, useful for debugging
  • The abort flag on a function (function! Foo() abort) converts any error inside into a thrown exception
  • Prefer catching specific error codes over bare :catch to avoid hiding unexpected bugs

Next

How do I enable matchit so % jumps between if/else/end style pairs?