LoginSignup
3
0

More than 1 year has passed since last update.

RubyのC拡張で例外クラスを定義する方法

Last updated at Posted at 2022-05-13

はじめに

Ruby言語では、StandardErrorを継承して例外を定義する。

class NoIndexError < StandardError; end

RubyのC拡張ライブラリ(Ruby C extension)で例外クラスを定義したい。

やり方

例外クラスを定義する

C拡張を書く時もRuby言語とまったく同じように、StandardErrorを継承したクラスを定義すればよい。
以下のようにして例外を定義できた。

VALUE rb_Bio;
VALUE rb_CGRanges;
VALUE rb_eNoIndexError;

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);
// 以下略

例外を呼び出す

rb_raise を使えばよい。
ここでは、インスタンス変数 @indexed をチェックして、true だった場合には例外を発生させる。
RTEST は、true/false を判定してくれる。

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

動作を確認する

test/unit を使っているので、下記のようにテストを作成した。
期待通り例外を発生させることができた。

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

この記事は以上です。

よい一日を。

3
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0