Rescuing SyntaxError

C

Caleb Tennis

Is it possible to catch illegal syntax errors?


irb(main):001:0> 550p
SyntaxError: compile error

...

# se.rb
begin
550p
rescue SyntaxError => e
# This never seems to get run
puts "Caught a syntax error: " + e
end

~> ruby se.rb
blah.rb:2: syntax error

Thanks,
Caleb
 
L

Logan Capaldo

Is it possible to catch illegal syntax errors?


irb(main):001:0> 550p
SyntaxError: compile error

...

# se.rb
begin
550p
rescue SyntaxError => e
# This never seems to get run
puts "Caught a syntax error: " + e
end

~> ruby se.rb
blah.rb:2: syntax error

Thanks,
Caleb

Sort of, you have to delay the compilation though:

irb(main):017:0> begin
irb(main):018:1* eval "550p"
irb(main):019:1> rescue SyntaxError => e
irb(main):020:1> puts "Caught a syntax error: " + e
irb(main):021:1> end
Caught a syntax error: (eval):1:in `irb_binding': compile error
(eval):1: syntax error
=> nil
 
C

Caleb Tennis

The reason the inner rescue is not triggered is that the exception
occurs while eval is turning the string into a parse tree, before it
starts executing the parse tree.

--

Sure thing. Is there any way to catch it though?
 
D

Devin Mullins

Caleb said:
Sure thing. Is there any way to catch it though?

begin
puts "this is text
rescue SyntaxError
puts "Syntax Error!"
end
__END__

No. How is Ruby supposed to know that the rescue block isn't supposed to
be part of that unterminated puts string from the line before? Do the
eval, load, or require thing as suggested.

Devin
 
P

Patrick Gundlach

Sure thing. Is there any way to catch it though?

Yes, when you read from a file:

begin
require "errorfile"
rescue SyntaxError
puts "Syntax Error!"
end


erorfile.rb:
 
C

Caleb Tennis

No. How is Ruby supposed to know that the rescue block isn't
supposed to be part of that unterminated puts string from the line
before? Do the eval, load, or require thing as suggested.

Yeah, I will. That's what will work in what I'm trying to do
anyway. Thanks.

Caleb
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top