DEV Community

kojix2
kojix2

Posted on

How to define exceptions in Ruby C extension library

introduction

In the Ruby language, exceptions are defined by inheriting StandardError.

class IndexedError < StandardError; end
Enter fullscreen mode Exit fullscreen mode

So how do you define an exception class in Ruby C extension library?

Define a exception class in C

When writing C extensions, exceptions can be defined in exactly the same way as in the Ruby language.

VALUE rb_Bio;
VALUE rb_CGRanges;
VALUE rb_eIndexedError;

void Init_cgranges(void)
{
  rb_Bio = rb_define_module("Bio");
  rb_CGRanges = rb_define_class_under(rb_Bio, "CGRanges", rb_cObject);
  rb_eIndexedError = rb_define_class_under(rb_CGRanges, "IndexedError", rb_eStandardError);
// ...
Enter fullscreen mode Exit fullscreen mode

Call exception

You can use rb_raise.

  if (RTEST(rb_ivar_get(self, rb_intern("@indexed"))))
  {
    rb_raise(rb_eIndexedError, "Cannot add intervals to an indexed CGRanges");
    return Qnil;
  }
Enter fullscreen mode Exit fullscreen mode

Here, the instance variable @indexd is checked and if it is true, an exception is raised.
RTEST will determine true or false.

Write a test

Using test/unit, I wrote a test as follows.
It raised an exception as expected.

cgranges.index
assert_raises(Bio::CGRanges::IndexedError) do
  cgranges.add("chr1", 10, 20, 0)
end
Enter fullscreen mode Exit fullscreen mode

That is all. Have a good day.

Top comments (0)