Syntax errors are one of the most basic errors in Ruby and are encountered when the Ruby compiler cannot parse your code. Here is an example:

# hello-world.rb x = { id: 1

ruby hello-world.rb hello-world.rb:1: syntax error, unexpected end-of-input, expecting '}'

In this block of code, we forgot to close the hash literal using a closing curly bracket } and the ruby parser isn't able to make sense of our code. And, since a SyntaxError is thrown by the ruby parser before it is executed, it cannot be rescued. This usually points to something unrecoverable. You may also run into this when you compile a piece of code at runtime or include new ruby files:

eval "x = {id: 1"

This block of code tries to compile our previous example using the eval function while our ruby code is being executed. Since ruby is an interpreted language the distinction between runtime and compile time is blurry. When your ruby code is executed it is first parsed and compiled by the ruby compiler and then executed. And SyntaxError s are usually raised when ruby is trying to parse your code.

You can catch a syntax error if it is being raised while eval ing a string or while require ing a ruby source file.

Capture a syntax error while eval ing:

begin eval 'x = {id: 1' rescue SyntaxError => err puts "ERROR: #{ err . inspect } " end

Capture a syntax error while require ing a ruby source file:

begin require 'syntax_error_demo' rescue SyntaxError => err puts "ERROR: #{ err . inspect } " end