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
:tryopens the guarded block:catch /{pattern}/intercepts exceptions whose message matches the regexv:exceptionholds the exception string inside a:catchblock:finallyruns unconditionally (useful for cleanup):endtrycloses 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
:catchwith no argument catches all exceptions- Vim's built-in errors follow the pattern
E{number}: catch/E\d\+/to catch any Vim error v:throwpointgives the script location where the exception was raised, useful for debugging- The
abortflag on a function (function! Foo() abort) converts any error inside into a thrown exception - Prefer catching specific error codes over bare
:catchto avoid hiding unexpected bugs