Rescuing SyntaxError


#1

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


#2

On Dec 17, 2005, at 3:04 PM, Caleb T. wrote:

550p

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


#3

Caleb T. wrote:

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

[~/tmp] cat se2.rb
begin
eval <<-END
begin
550p
rescue SyntaxError => e
# This never seems to get run
puts "Caught a syntax error: " + e
end
END
rescue SyntaxError
puts “Caught a syntax error during eval”
end
[~/tmp] ruby se2.rb
Caught a syntax error during eval

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.


#4

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?


#5

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:

puts "this is a string

This is what I use with my cgi scripts / PrettyException.rb

Patrick


#6

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


#7

Caleb T. wrote:

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?

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