diff --git a/src/operators.c b/src/operators.c
index 5f10b36132776d69675df613f97fc6a88c824091..655ce520e8791404f000d3d5943b96418790cc16 100644
--- a/src/operators.c
+++ b/src/operators.c
@@ -261,6 +261,8 @@ PMOD_EXPORT void o_cast_to_int(void)
 	Pike_error("Cast failed, wanted int, got %s\n",
 		   get_name_of_type(TYPEOF(sp[-1])));
       }
+      else if(SUBTYPEOF(sp[-1]) == NUMBER_UNDEFINED)
+        Pike_error("Cannot cast this object to int.\n");
     }
 
     break;
@@ -342,6 +344,8 @@ PMOD_EXPORT void o_cast_to_string(void)
 
       if(TYPEOF(sp[-1]) != PIKE_T_STRING)
       {
+        if(TYPEOF(sp[-1])==PIKE_T_INT && SUBTYPEOF(sp[-1])==NUMBER_UNDEFINED)
+           Pike_error("Cannot cast this object to string.\n");
 	if(TYPEOF(sp[-1]) == T_OBJECT && sp[-1].u.object->prog)
 	{
 	  struct object *o = sp[-1].u.object;
@@ -725,6 +729,11 @@ PMOD_EXPORT void o_cast(struct pike_type *type, INT32 run_time_type)
     }
   }
 
+  if(TYPEOF(sp[-1]) == T_INT &&
+     SUBTYPEOF(sp[-1]) == NUMBER_UNDEFINED)
+    Pike_error("Cannot cast this object to %s.\n",
+               get_name_of_type(type->type));
+
   if(run_time_type != TYPEOF(sp[-1]))
   {
     switch(TYPEOF(sp[-1])) {
diff --git a/src/testsuite.in b/src/testsuite.in
index 8d22eee838b20fcafa4a073d1a30164f783f4fb9..3e19916f86f7118f1343e52e8d581d974ffda5e9 100644
--- a/src/testsuite.in
+++ b/src/testsuite.in
@@ -8604,6 +8604,9 @@ test_eq([[(string) ({'z', 0x7fffffff, '.'})]], "z\x7fffffff.")
 test_eval_error([[(string) ({0x80000000})]])
 test_eq([[(string) ({'z', -0x80000000, '.'})]], "z\x80000000.")
 test_eval_error([[(string) ({-0x80000001})]])
+test_eval_error([[(int)class { mixed cast() { return UNDEFINED; } }();]])
+test_eval_error([[(string)class { mixed cast() { return UNDEFINED; } }();]])
+test_eval_error([[(mapping)class { mixed cast() { return UNDEFINED; } }();]])
 
 // testing @
 test_equal(({1,2,3}),lambda(mixed ... x) { return x; }(@a()))