18
\$\begingroup\$

Your task is to create a program or function which randomly errors. Specifically, there must be a nonzero probability of erroring, but also a nonzero probability of running without error.

An error is anything that causes a program to terminate abnormally, such as dividing by zero or using an uninitialized variable. This also includes runtime errors, syntax errors and errors while compiling. Statements which manually throw an error, such as JavaScript's throw are allowed.

This program doesn't need to do anything if it doesn't error, other than exiting gracefully.

This is , so shortest answer per language wins.

Note: For this challenge, "randomly" follows the current consensus (so no using undefined behavior or uninitialized memory for randomness), and the program must be capable of producing both outputs if run or compiled multiple times (so a random number with the same seed is not valid)

\$\endgroup\$
18
  • 19
    \$\begingroup\$ I think it's a boring challenge. A lot of the answers are doing basically the same thing and there's little room for golfing. Note that downvotes don't necessarily indicate a challenge is ill-specified -- there's close votes for that. \$\endgroup\$
    – xnor
    Commented Apr 10, 2020 at 15:43
  • 3
    \$\begingroup\$ Separately, I'm not so sure it's clear, since two of the upvoted answers rely on the state of memory when the program starts, despite the question in my earlier comment. \$\endgroup\$
    – xnor
    Commented Apr 10, 2020 at 15:45
  • 4
    \$\begingroup\$ I don't really think the current definition of random, although settled, is really clear. For example, the python answer and the brainfuck answer below uses some degree of undefined behavior. The c answer, although fits that definition, won't really crash because of the lack of srand. So, I don't really like challenges based on such loose definitions (and when such definition matters a lot). I would change it to upvote if the question is updated, say, to, the program may or may not crash after a rerun/recompile. \$\endgroup\$
    – newbie
    Commented Apr 10, 2020 at 15:47
  • 5
    \$\begingroup\$ It seems like so many users are posting 1/(random integer) here... \$\endgroup\$ Commented Apr 11, 2020 at 1:33
  • 1
    \$\begingroup\$ @xnor: agreed, this turns out to be somewhat interesting in some assembly languages, but most high level languages make unpredictable behaviour intentionally difficult other than integer division, or a few other things where 0 is special. \$\endgroup\$ Commented Apr 11, 2020 at 4:40

65 Answers 65

2
\$\begingroup\$

Wolfram Language (Mathematica), 17 bytes

1/RandomInteger[]

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Erlang (escript), 22 bytes

Just like the other answers...

f()->1/rand:uniform().

Try it online!

\$\endgroup\$
2
\$\begingroup\$

C (gcc), 28 bytes

f(i){srand(&i);i/=rand()&1;}

Crashes approximately every other time it's run. Abuses ASLR.

Try it online!

\$\endgroup\$
5
  • \$\begingroup\$ Since we ultimately rely on &i for randomness, why not get rid of the rand stuff? f(i){i/=(int)&i<0;} works. \$\endgroup\$ Commented Apr 11, 2020 at 7:28
  • 2
    \$\begingroup\$ @SurculoseSputum Because then it would violate the rules for "randomly". \$\endgroup\$
    – S.S. Anne
    Commented Apr 11, 2020 at 13:46
  • 2
    \$\begingroup\$ I just reread the specification - apparently this challenge is much different than I thought... \$\endgroup\$ Commented Apr 11, 2020 at 16:04
  • \$\begingroup\$ @SurculoseSputum: I think that's a constant, but such an expression should exist. \$\endgroup\$
    – Joshua
    Commented Apr 24, 2020 at 23:00
  • \$\begingroup\$ -1 byte: f(i){i/=rand(srand(&i))&1;} \$\endgroup\$
    – jdt
    Commented Aug 22, 2021 at 10:20
2
\$\begingroup\$

Pyth, 3 bytes

-1 thanks to FryAmTheEggman.

lO2

Try it online!

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Using l is shorter than /1, though there still might be something better. \$\endgroup\$ Commented Apr 10, 2020 at 15:22
2
\$\begingroup\$

Keg, 3 bytes

~~/

Try it online!

This works by pushing two random numbers onto the stack ane dividing them. If the second number is 0, then it errors out.

There is indeed a chance for the second number to be 0, but it is highly unlikely that it will be, as the random range used is quite large. But highly unlikely != zero.

If I were to estimate the odds of erroring out, I'd say it'd be something like 1 in ((int​(​"​9​"​*​3234​) ** 2) + 21) * 2.

\$\endgroup\$
4
  • \$\begingroup\$ Hey, look, it worked: TypeError: integer argument expected, got float \$\endgroup\$
    – S.S. Anne
    Commented Apr 10, 2020 at 23:48
  • \$\begingroup\$ With a higher chance of erroring... ~:/ \$\endgroup\$
    – user92069
    Commented Apr 11, 2020 at 2:58
  • \$\begingroup\$ @petStorm that's still the same chance. \$\endgroup\$
    – lyxal
    Commented Apr 11, 2020 at 3:03
  • 1
    \$\begingroup\$ Is "highly unlikely != non-zero" intended to be "highly unlikely != zero"? \$\endgroup\$
    – L. F.
    Commented Apr 11, 2020 at 3:39
2
\$\begingroup\$

Bash, 1/32767 chance of success, 12 bytes

exit $RANDOM
\$\endgroup\$
2
\$\begingroup\$

PowerShell Windows, 10 bytes

ps(random)

get-random returns an int between 0 and 0x7FFFFFFF so it'll eventually match some PID and ps will get the process that are running on the local computer. Maybe...


PowerShell Linux, 11 bytes

gps(random)

TIO does not work because System.UnauthorizedAccessException. Please use your own Powershell. :)

\$\endgroup\$
2
\$\begingroup\$

Ruby, 9 bytes

1/rand(2)

Try it online!

\$\endgroup\$
0
2
\$\begingroup\$

Red - 24 bytes

x: now/time 1 / x/minute
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to the site, I've tried to correct the code formatting in your answer. You can revise it if I have something wrong. Let me know if you are having trouble with the formatting. \$\endgroup\$
    – Wheat Wizard
    Commented Apr 15, 2020 at 13:13
2
\$\begingroup\$

Batch, 11 bytes

%random:1=%

Has a probability of 1/65536 Corrected by @Neil, 5/32768 (~0.0015%) to not generate an error.

Edit: Alternatively,

%random:~1%
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 5/32768, I think? (1, 11, 111, 1111 and 11111 won't error, and %random% only goes from 0 to 32767.) \$\endgroup\$
    – Neil
    Commented Apr 13, 2020 at 13:48
  • \$\begingroup\$ @Neil you're right, will fix that \$\endgroup\$
    – ScriptKidd
    Commented Apr 13, 2020 at 14:44
2
\$\begingroup\$

Ahead, 4 bytes

50/50 chance of a divide by zero error. X causes the head to go in a random cardinal direction, / is obviously division, and @ ends the program. Because of edge bouncing, the head traveling up or left is the same as it traveling down or right since it's in a corner.

X/
@

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Ruby, 10 bytes

1.div rand

Can't do 1/rand, since 1/0.0 in Ruby is Infinity, not an error.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Vyxal, 3 bytes

∆Ṙl

Try it Online!

I think this has a \$\frac{1}{2^{19937}}\$ chance of not erroring, but I'm not sure - Vyxal is written in Python, so it's whatever chance python's PRNG has of returning 0.

\$\endgroup\$
2
\$\begingroup\$

Minim, 6 Bytes

[R*S].

Accesses memory at index RandomNumber times MemorySize.

R is between 0 and 1 inclusive, and S is the memory scope size in elements. If R = 1, then the index will be out of bounds, and throws an error.

GitHub Repository

\$\endgroup\$
2
\$\begingroup\$

Japt, 3 bytes

Feck it, may as well post this. Similar in concept to but derived independently from Etheryte's solution. Predicated on the fact that JavaScript's toString method can only handle bases 2-36 so it, therefotre, has a 20% chance of throwing a RangeError (toString() radix argument must be between 2 and 36) - change the A to alter the odds of an error occurring.

sAö

Test it (errors are displayed below the output field)

sAö     :Implicit input of integer U, defaulting to 0
s       :Convert to string in base
 A      :  10
  ö     :  Random integer from range [0,A)
\$\endgroup\$
2
\$\begingroup\$

JavaScript (Node.js), 17 15 14 bytes

new Date%2?a:0

Errors if current millisecond is odd

new Date returns current epoch time
%2 modulo 2, returns 1 if odd, 0 if even
if it's a truthy value (1), a will throw as it's an undefined variable

Try it online!

\$\endgroup\$
6
  • 2
    \$\begingroup\$ new Date should work instead of Date.now(), saving 2 bytes. You could also replace the throw 1 with something like a (which causes a ReferenceError). \$\endgroup\$ Commented Aug 20, 2021 at 13:25
  • \$\begingroup\$ i never knew new doesn't require (), i completely forgot about reference error lol \$\endgroup\$
    – mekb
    Commented Aug 21, 2021 at 5:50
  • 1
    \$\begingroup\$ You can save a byte with new Date%2?a:0 \$\endgroup\$
    – Ectogen
    Commented Aug 21, 2021 at 7:11
  • 1
    \$\begingroup\$ ah yes, ternary, the thing i overuse the most in js \$\endgroup\$
    – mekb
    Commented Aug 21, 2021 at 7:25
  • \$\begingroup\$ @Ectogen Or another with new Date%2&&a, but then it's identical to mine \$\endgroup\$ Commented Aug 21, 2021 at 17:57
2
\$\begingroup\$

Trilangle, 5 bytes

Contains invalid UTF-8, so I can't post it here. Instead, have a hexdump reversible with xxd -r:

00000000: 2437 40f7 2e                             $7@..

When reading the file, the interpreter starts by loading it as UTF-8 and converting it to a list of 24-bit integers (effectively UTF-32 on many machines due to struct padding). If it encounters an invalid UTF-8 sequence, it doesn't immediately error; rather, it takes that character as U+FFFD and keeps going. Once it's done, it makes the program length be a triangular number by appending . (U+002E) as necessary.

Currently, the interpreter stops with an error when it attempts to execute a character that isn't a valid opcode, but this behavior isn't specified. Any invalid opcode I choose could be added in the future, invalidating my answer.

Any character, that is, except for U+FFFD. When the interpreter attempts to execute 0xfffd, it writes an error message to STDERR and exits with code 1:

Unicode replacement character (U+FFFD) detected in source. Please check encoding.

The sequence f72e is invalid UTF-8, so when the program is loaded in it looks like this:

  $
 7 @
� . .

The $ instruction pushes a random integer to the stack, uniformly distributed in the range [-8 388 608, 8 388 607]. Then, 7 is a branch instruction based on the sign of the value on top of the stack. If the value is positive, the IP reaches the @, terminating the program gracefully. If the value is negative, the IP reaches the invalid character, triggering the encoding error.

\$\endgroup\$
2
\$\begingroup\$

Pip, 4 bytes

VRCk

Attempt This Online!

Explanation

k is a preinitialized variable containing the string , . RC chooses one of its characters at random, and V attempts to evaluate it as Pip code. If the space was chosen, the evaluation is successful and returns nil. If the comma was chosen, the interpreter crashes:

Fatal error during execution: Parsing error while evaluating ",": Hit end of tokens while parsing expression
Program terminated.
\$\endgroup\$
2
  • \$\begingroup\$ A bit boring, but /r works if you add -w \$\endgroup\$
    – emanresu A
    Commented Aug 10, 2023 at 23:25
  • \$\begingroup\$ @emanresuA That's a warning, not an error--the difference being that it doesn't cause the program to terminate abnormally, as specified in the challenge. \$\endgroup\$
    – DLosc
    Commented Aug 11, 2023 at 23:36
2
\$\begingroup\$

05AB1E, 3 bytes

®ΩF

Try it online! Has a \$\frac12\$ chance of erroring.

®ΩF  # full program
  F  # for N in (0, ...
 Ω   # random element from...
®    # register_c (starts at -1)...
     # (implicit) split into separate characters...
  F  # ... - 1)...
     # (implicit) do nothing
     # (implicit) end loop

-1 split into separate characters is ["-", "1"], so it picks a random element from there. Either it picks 1 and does nothing once, or it picks -, tries to loop - times, and crashes. Unlike ï, the built-in integer conversion function, it doesn't handle errors (if it can't be converted to an integer). So, it throws an error.

\$\endgroup\$
1
\$\begingroup\$

brainfuck, 2 bytes

Sometimes segfaults, sometimes doesn't.

<.

Try it online!

\$\endgroup\$
5
  • 5
    \$\begingroup\$ Isn't this implementation based, not random? \$\endgroup\$ Commented Apr 10, 2020 at 14:27
  • \$\begingroup\$ sometimes malloc allocates a bigger page so you can read something before the tape, and sometimes malloc allocates smaller page so reading something before the tape segfaults \$\endgroup\$ Commented Apr 10, 2020 at 14:28
  • \$\begingroup\$ personally after mashing the run button for a while, I've seen two segfaults so far \$\endgroup\$ Commented Apr 10, 2020 at 14:29
  • \$\begingroup\$ That's just because you're mashing the run button too fast. Also, this uses neither options 1, 2, nor 3 from the meta consensus. \$\endgroup\$
    – S.S. Anne
    Commented Apr 10, 2020 at 23:34
  • \$\begingroup\$ +[<[-]+] doesn't segfault on TIO, so I don't think this is valid. In fact, if the [-] is removed, it halts, so the tape is seemingly looped. \$\endgroup\$ Commented Apr 11, 2020 at 3:31
1
\$\begingroup\$

Windows Batch, 1715 bytes

set/a1/%random%
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I don't think you need the x=. \$\endgroup\$
    – Neil
    Commented Apr 10, 2020 at 23:34
  • \$\begingroup\$ indeed, -2 bytes thanks to @Neil \$\endgroup\$ Commented Apr 17, 2020 at 22:42
1
\$\begingroup\$

VBA, 46 42 35 25 13 bytes

Thanks to @Taylor Scott

?1/Int(9*Rnd)

This code only works inside the Immediate Window.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ If you make this an immediate window function, you can get it down to ?1/Int(9*rnd) \$\endgroup\$ Commented May 26, 2020 at 19:48
  • 1
    \$\begingroup\$ @Taylor Scott, I didn't know you can do that. Thanks, mate. \$\endgroup\$ Commented Jul 1, 2020 at 1:53
1
\$\begingroup\$

Befunge-98 (FBBI), 4 bytes

?@
=

Executing = is of the only ways I can get Befunge to actually error (a / won't work there because 0/0 evaulates to 0 in Befunge-98 and asks the user in Befunge-93).

Try it online!

The ? turns the IP in a random direction. If it goes horizontally (1/2 chance), it hits the @ and terminates successfully. If it goes vertically, it hits the = and uses the empty stack (interpreted as the empty string) as the argument. This throws a segfault in FBBI (which implements = as a C system() call).

\$\endgroup\$
1
\$\begingroup\$

Jelly, 4 bytes

9XRy

Try it online!

Errors roughly 55% of the time

How it works

9XRy - Main link. Takes no arguments
9X   - Generate a random number from 1 to 9
  R  - Get the range from 1 to that number
   y - Translate, by pairs

y splits a flat array [a, b, c, d, ..., y, z] into pairs, [[a, b], [c, d], ..., [y, z]], then replaces a with b, c with d etc in the right argument. However, if there are an odd number of elements in the array, it attempts to pop from an empty list when doing the substitution, which errors.

\$\endgroup\$
1
\$\begingroup\$

Japt, 3 bytes

Throws if seconds in a new date object are less than 2 or more than 36 since values outside of that range are not valid for base conversion in Japt.

sKb
s   // Try to convert the input to a string in base
 K  // new Date()
  b // get seconds.

Try it here.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Nice! I had something similar in sAö. \$\endgroup\$
    – Shaggy
    Commented Aug 16, 2021 at 20:10
1
\$\begingroup\$

Java (JDK), 18 bytes

a->1/Math.random()

Try it online!

Well yeah, essentially the answer everyone gave but I didn't see Java yet. For the completeness.

\$\endgroup\$
1
\$\begingroup\$

Perl 5, 10 bytes

1/(time%2)

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Pyt, 2 bytes

ɽ⅟

Try it online!

ɽ         gets a random 32-bit integer
 ⅟        takes the multiplicative inverse; implicit print

Errors on division by 0

\$\endgroup\$
1
\$\begingroup\$

GolfScript, 12 11 bytes

2rand{/}1if

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Fortran (GFortran), 16 bytes

j=1/mod(i,2)
end

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.