DEV Community

kojix2
kojix2

Posted on

4 4

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up