Exception: KeyError

Inherits:
IndexError show all
Defined in:
error.c,
error.c

Overview

Raised when the specified key is not found. It is a subclass of IndexError.

h = {"foo" => :bar}
h.fetch("foo") #=> :bar
h.fetch("baz") #=> KeyError: key not found: "baz"

Instance Method Summary collapse

Methods inherited from Exception

#==, #backtrace, #backtrace_locations, #cause, #exception, exception, #full_message, #inspect, #message, #set_backtrace, #to_s, to_tty?

Constructor Details

#new(message = nil, receiver: nil, key: nil) ⇒ Object

Construct a new KeyError exception with the given message, receiver and key.



1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
# File 'error.c', line 1938

static VALUE
key_err_initialize(int argc, VALUE *argv, VALUE self)
{
    VALUE options;

    rb_call_super(rb_scan_args(argc, argv, "01:", NULL, &options), argv);

    if (!NIL_P(options)) {
	ID keywords[2];
	VALUE values[numberof(keywords)];
	int i;
	keywords[0] = id_receiver;
	keywords[1] = id_key;
	rb_get_kwargs(options, keywords, 0, numberof(values), values);
	for (i = 0; i < numberof(values); ++i) {
	    if (values[i] != Qundef) {
		rb_ivar_set(self, keywords[i], values[i]);
	    }
	}
    }

    return self;
}

Instance Method Details

#keyObject

Return the key caused this KeyError exception.

Returns:



1909
1910
1911
1912
1913
1914
1915
1916
1917
# File 'error.c', line 1909

static VALUE
key_err_key(VALUE self)
{
    VALUE key;

    key = rb_ivar_lookup(self, id_key, Qundef);
    if (key != Qundef) return key;
    rb_raise(rb_eArgError, "no key is available");
}

#receiverObject

Return the receiver associated with this KeyError exception.

Returns:



1892
1893
1894
1895
1896
1897
1898
1899
1900
# File 'error.c', line 1892

static VALUE
key_err_receiver(VALUE self)
{
    VALUE recv;

    recv = rb_ivar_lookup(self, id_receiver, Qundef);
    if (recv != Qundef) return recv;
    rb_raise(rb_eArgError, "no receiver is available");
}