# Make your code error, but only sometimes!

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)

• 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.
– xnor
Apr 10, 2020 at 15:43
• 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.
– xnor
Apr 10, 2020 at 15:45
• 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. Apr 10, 2020 at 15:47
• It seems like so many users are posting 1/(random integer) here... Apr 11, 2020 at 1:33
• @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. Apr 11, 2020 at 4:40

# Erlang (escript), 22 bytes

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


Try it online!

# C (gcc), 28 bytes

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


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

Try it online!

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

# Pyth, 3 bytes

-1 thanks to FryAmTheEggman.

lO2


Try it online!

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

# 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.

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

# Bash, 1/32767 chance of success, 12 bytes

exit \$RANDOM


# 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. :)

Ruby, 9 bytes

1/rand(2)


Try it online!

• While very concise, I'm not too sure if this approach works: rand returns a Float, but 1 / 0.0 is Infinity, not an exception. (That's at least in Ruby 2.6, the behaviour might be different in older versions.) Apr 11, 2020 at 11:23
• Damn you're right. Apr 11, 2020 at 17:00

# Red - 24 bytes

x: now/time 1 / x/minute

• 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. Apr 15, 2020 at 13:13

# 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%

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

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!

# 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!

# 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.

# 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

# JavaScript (Node.js), 1715 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!

• 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). Aug 20, 2021 at 13:25
• i never knew new doesn't require (), i completely forgot about reference error lol
– mekb
Aug 21, 2021 at 5:50
• You can save a byte with new Date%2?a:0 Aug 21, 2021 at 7:11
• ah yes, ternary, the thing i overuse the most in js
– mekb
Aug 21, 2021 at 7:25
• @Ectogen Or another with new Date%2&&a, but then it's identical to mine Aug 21, 2021 at 17:57

# Aussie++, 78 bytes

G'DAY MATE!
IMPOHT ME FUNC ChuckSomeDice;
ChuckSomeDice(0,ChuckSomeDice(0,2));


Tested in commit 9522366.

ChuckSomeDice is the only way to get a random number, but it behaves a bit interestingly:

• If either argument is a finite non-integer, it's truncated to an integer.
• Inputs are capped to be no greater than 9223372036854775296.
• NaN is treated as 0.
• If both arguments (let's call them x and y) are integers, and y is greater than x, it gets a random integer in [x, y).
• If x is less than y, it prints OI MATE, CAN YA FUCKIN' COUNT?? START MUST BE LESS THAN END!! to STDERR, but continues execution.
• If x is equal to y, it panics. See this Github issue.

The result is stored as a double, so calling e.g. ChuckSomeDice(9223372036854775295, 1/0) only ever produces either 9223372036854775000 or 9223372036854776000.

TL;DR: The arguments can't be equal, and behind the scenes it's likely casting between i64 and f64.

So, I get either 0 or 1 randomly, and then get a random number between 0 and the result. If that was also 0, it panics. If that was 1, it returns 0.

# brainfuck, 2 bytes

Sometimes segfaults, sometimes doesn't.

<.


Try it online!

• Isn't this implementation based, not random? Apr 10, 2020 at 14:27
• 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 Apr 10, 2020 at 14:28
• personally after mashing the run button for a while, I've seen two segfaults so far Apr 10, 2020 at 14:29
• 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. Apr 10, 2020 at 23:34
• +[<[-]+] 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. Apr 11, 2020 at 3:31

## Windows Batch, 1715 bytes

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

## VBA, 46423525 13 bytes

Thanks to @Taylor Scott

?1/Int(9*Rnd)


This code only works inside the Immediate Window.

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

# 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).

# 05AB1E, 3 bytes

®Ωι


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

®Ωι  # full program
ι  # uninterleave...
Ω   # random element from...
®    # register_c (starts at -1)...
# (implicit) split into separate characters...
ι  # lists which were interleaved together into...
# (implicit) stack is empty, so bottom of stack...
# (implicit) converted to list


-1 split into separate characters is ["-", "1"], so it picks a random element from there. Either it picks 1 and uninterleaves 1 list which was interleaved into ["1"] (one list interleaved is the same list, so it returns ["1"]), or it picks -, and tries to uninterleave - lists which were interleaved together into ["-"]. 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.

# 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.

# 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.

• Nice! I had something similar in sAö. Aug 16, 2021 at 20:10

# 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.

# 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)


# Perl 5, 8 bytes

1/($$%2)  Here $$ is current PID.

Try it online!

• The current PID is not considered random for this challenge. Aug 22, 2021 at 18:55

# Perl 5, 10 bytes

1/(time%2)


Try it online!

## (plain) pdfTeX, 34 bytes

\ifcase\pdfuniformdeviate9}\fi\bye


# Commodore BASIC (Commodore C64/128, VIC-20, C16/+4, PET, Ultimate64, THEC64 etc)

0 on6*rnd(.)goto10,20,30,40,50:goto
10 print"working":goto
20 print"working":goto
30 print"working":goto
40 print"working":goto


I've put a prompt in just to show that it does work sometimes too. Essentially, it breaks when the random number generated is rounded to 5 (it generates floating point numbers, but the BASIC interpreter ignores the decimal places).