g | x | w | all
Bytes Lang Time Link
003Volatile230908T204342Zbluswimm
00305AB1E210107T013346ZMakonede
004Pip230810T221805ZDLosc
005Trilangle230214T173818ZBbrk24
016Fortran GFortran230214T065004Zroblogic
011GolfScript230210T142858Zemirps
002Pyt230210T140228ZKip the
078Aussie++220401T023326ZBbrk24
064Commodore BASIC Commodore C64/128210824T130741ZShaun Be
010Perl 5210823T075207ZDenis Ib
034plain pdfTeX210822T044345Zplante
014JavaScript Node.js210820T065107Zmekb
003Japt210820T144128ZShaggy
018Java JDK210820T134413Z0xff
003Japt210816T184840ZEtheryte
024C clang210816T134936Zjdt
004><>210815T085502Zaaa
024Python <= 3.7210813T133542ZAlex Way
006Minim210814T004126ZChristia
006J200410T143318ZJonah
007Zsh210326T150045Zpxeger
004Jelly210618T182219Zcaird co
003Knight210615T143020ZEasyasPi
003Vyxal210615T044345Zemanresu
010Ruby210326T145058ZYelp
004Ahead210107T020525Zsnail_
004Befunge98 FBBI200701T161045ZPizgenal
013VBA200420T053607Zネルマン
005Z80 machine code200419T191156ZStefan P
011Batch200411T095327ZScriptKi
015Windows Batch200410T185824Zpeter fe
024Red200415T125126ZAngryTon
003Metatape200414T204206ZCloudy7
008Google Sheets200413T180229ZEngineer
209Taxi200413T175352ZEngineer
013JavaScript V8200410T142151ZRydwolf
nanCompiled Stax200412T233009ZJoshua
000Baby Language200410T172630ZAviFS
nanincludes 3 different answers200411T042914ZPeter Co
009Ruby200410T233353ZArmand F
016C gcc200410T142246ZNoodle9
008Bash + Unix utilities200410T144747ZMitchell
010PowerShell Windows200411T090625Zmazzy
014R200411T072555ZRobin Ry
003><>200411T073536ZDion
005><>200410T150144ZPkmnQ
012Bash200411T064421Zl0b0
003Keg200410T214155Zlyxal
003Pyth200410T141433Zuser9206
028C gcc200410T234623ZS.S. Ann
010INTERCAL200410T232446ZMark
912Lost A200410T185652ZWheat Wi
033SQL Oracle200410T193514ZDel
010PowerShell200410T193000ZVeskah
00405AB1E200410T173621ZExpired
003APL Dyalog Unicode200410T165534ZAviFS
013Octave / MATLAB200410T163535ZLuis Men
011Python 3200410T142553ZSurculos
005Jelly200410T143626Zuser9206
022Erlang escript200410T143224Zuser9206
002brainfuck200410T142616ZKamila S
017Wolfram Language Mathematica200410T141313ZZaMoC
002Charcoal200410T140345ZNeil

Volatile, 3 bytes

~~/

~ pushes a random number onto the stack (which may include zero), and / pops two numbers and divides them. If the first ~ pushes a zero, then the program errors.

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.

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.

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.

Fortran (GFortran), 16 bytes

j=1/mod(i,2)
end

Try it online!

GolfScript, 12 11 bytes

2rand{/}1if

Try it online!

Pyt, 2 bytes

ɽ⅟

Try it online!

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

Errors on division by 0

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:

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.

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

Commodore C64 BASIC working or not

Perl 5, 10 bytes

1/(time%2)

Try it online!

(plain) pdfTeX, 34 bytes

\ifcase\pdfuniformdeviate9}\fi\bye

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!

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)

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

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.

C (clang), 24 bytes

main(i){i/=(time(0)%3);}

Try it online!

C, 20 bytes

main(i){i/=time(0);};

Will crash once every +/- 68 years.

https://en.wikipedia.org/wiki/Year_2038_problem

><>, 4 bytes

The ! skips the next instruction, even if it would give an error. The x set the pointer's direction to a random direction. It can make it go up or down but if the pointer reaches the edge then it wraps around. The ; ends the program. The { can be replaced with any character as long as it's not a valid command in ><>.

!{x;

https://tio.run/##S8sszvj/X7G6wvr/fwA Try it online!

Python <= 3.7, 25 24 bytes

lambda x:id(x.__dir__)

Included for its weirdness rather than its brevity. This will cause a segmentation fault in obscure cases involving deep recursion. A fix is being applied, but only to python versions >=3.8.

The crash only occurs on cleanup when exiting the interpreter, but an example of how to call this function (and reproduce the segfault) can be found here: Try it online!

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

J, 6 byte function

z^:?@2

Try it online!

If y is the argument, z^:v conditionally returns the result z y if v y returns 1. Otherwise it returns y unchanged.

? 2 will return 0 half the time and 1 half the time.

No matter what argument we pass to this function, it will be converted into the constant 2 and then passed to z^:?.

So half time the result will be 2, and half the time it will error when trying to execute the non-existent verb z.

alternative full programs

Though these may look like snippets they should count as full programs in the context of this challenge.

4 bytes thanks to Bubbler:

q:?2

5 bytes thanks to Adam:

0^.?2

Zsh, 8 7 bytes, \$ \approx \frac{1}{10}\$ chance of success

>$$
<*4

Attempt This Online!

Determines whether the process ID ends in 4.

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.

Knight, 3 bytes

/1R

Try it online!

Has a roughly \$\frac{1}{65536}\$ chance of dividing by zero.

The classic 1/rand() trick. Assumes that dividing by zero throws an error, of course.

Uncommenting the line at the top of the header code will srand with a seed that will cause glibc's rand() to return 0xe7d0000, which when masked by 0xFFFF, results in 0.

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.

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!

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!

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

VBA, 46 42 35 25 13 bytes

Thanks to @Taylor Scott

?1/Int(9*Rnd)

This code only works inside the Immediate Window.

Z80 machine code, 6 5 bytes

I finally managed to reduce it to 5 bytes and also make it more well-behaved at the same time:

ED 5F B7 C0 76

Explanation:

ED 5F   LD A, R  ; get non-deterministic value (00-7F) from memory refresh register
B7      OR A, A  ; set Z flag if A is zero
C0      RET NZ   ; return normally, unless we were unlucky and got zero
76      HALT     ; halt the CPU

Alternatively to the HALT instruction RST could be used to call an error handler.

Other approaches that use 6 bytes and fail in a less well-behaved way:


ED 5F 17 32 06 00

Explanation:

ED 5F      LD A, R       ; get random value (00-7F) from refresh count register
17         RLA           ; rotate left one
32 06 00   LD (0006), A  ; write the byte immediately following this instruction.

There is a chance that this results in one of the conditional RET instructions to be written after the code, which returns normally if the condition happens to be met, which is the case for RET NZ (C0), RET NC (D0), RET PE (E8) and RET M (F8). Otherwise, a random instruction is executed and the program counter runs into whatever is in RAM after that, failing horribly. If bit 8 of the R register was somehow set (which doesn't normally happen), or any instruction with an opcode up to 7F would somehow end the program normally, this could be reduced to 5 bytes. The address operand in the last instruction must be set relative to where the code is actually located.


ED 5F B7 28 FE C9

Explanation:

ED 5F   LD A, R  ; get non-deterministic value (00-7F) from memory refresh register
B7      OR A, A  ; set Z flag if A is zero
28 FE   JR Z, -2 ; infinite loop if Z-flag is set
C9      RET      ; return

An infinite loop might not really count as an 'error' though. An alternative solution (same length), inspired by Peter Cordes' x86 solution, is to mess with the return address:


E5 ED 5F AC 67 E9

Explanation:

E5      POP HL   ; get return address from stack
ED 5F   LD A, R  ; get non-deterministic value (00-7F) from memory refresh register
AC      XOR A, H ; this will only leave H intact 
67      LD H, A  ;       if R was zero by chance
E9      JP HL    ; jump to (probably broken) return address

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%

Windows Batch, 1715 bytes

set/a1/%random%

Red - 24 bytes

x: now/time 1 / x/minute

Metatape, 4 3 bytes

x?(

-1 byte thanks to Hactar, the language creator, on Discord

Initially, the tape head is within a tape and pointing to a null cell. The command x exits the current cell, creating a new tape and putting the initial tape within it. Now the tape head is within a tape and pointing at a tape.

The ? command then generates a random bit, setting the current cell of the tape to null if it is 0 and doing nothing if it is 1. Then the ( command jumps to the next | or ) characters in the code if and only if the current cell is null, and does nothing otherwise. Thus, if the bit generated by ? is 0, the interpreter will throw an error, as there is no | or ) to jump to. On the other hand, Metatape does not implicitly check for every ( matching with a ), so if the bit generated by ? is 1, no error will be thrown.

EDIT: After further clarification with the language's creator, I found that the last sentence I wrote may not apply to all interpreters, and thus this answer might not work for all interpreters. Oops.

Google Sheets, 8 bytes

=0/RAND(

Google will a closing parentheses automatically to give =0/RAND().

Since RAND() produces a uniformly random between 0 inclusive and 1 exclusive and to 15 decimal points of accuracy, is has a 0.0000000000001% chance of returning exactly 0 and causing the #DIV/0! error.

Taxi, 209 bytes

Go to Heisenberg's:w 1 r 3 r 1 l.Pickup a passenger going to Magic Eight.Pickup a passenger going to Magic Eight.Go to Magic Eight:s 1 r 1 l 3 r.Pickup a passenger going to Cyclone.Go to Taxi Garage:e 2 l 2 r.

Try it online!

Ungolfed and commented:

[ Heisenberg's produces random integers ]
Go to Heisenberg's:w 1 r 3 r 1 l.
[ Pickup two random integers ]
Pickup a passenger going to Magic Eight.
Pickup a passenger going to Magic Eight.
[ Magic Eight compares two numeric passengers ]
[ It returns the first passenger if it is less than the second and no one if it is not ]
Go to Magic Eight:s 1 r 1 l 3 r.
[ Try to pickup a passenger, which will error if there isn't anyone waiting ]
Pickup a passenger going to Cyclone.
[ Return to the garage to avoid getting the "you're fired" error ]
Go to Taxi Garage:e 2 l 2 r.

Try the ungolfed and commented version online!

JavaScript (V8), 15 13 bytes

idea and -2 bytes from @apsillers

Uses new Date instead of Math.random, has a \$\frac{1}{9}\$ chance of not erroring:

new Date%9&&a

Try it online!

JavaScript (V8), 17 16 bytes

-1 thanks to @newbie

Math.random()&&a

Try it online!

This has a \$\frac{1}{2^{1074}}\$ chance of not erroring, as Math.random() can occasionally be 0.

Compiled Stax, 28 27 25 bytes

Requires 116 TB RAM, and ulimit -s set to 116TB.

8000000000000{1-cy{}?}Y!

At present time, obvious ways to golf this fail to compile due to the compiler not supporting the requisite language feature.

This program attempts a recursive block invocation with a depth of 8000000000000, which in turn tries to create 8000000000000 16 byte stack frames on the runtime stack. This either succeeds or fails with probability of about .5 depending on how far apart the program and the top of the stack are in address space are.

I am using the environment's RNG that is actually documented to be random to make this fault or not fault.

And recursive said there's no such thing as nondetermistic stax.

Baby Language, 0 bytes


Try it online!

I knew this could be fun with a non-deterministic tarpit! I looked through the category on the Esolang wiki and found this language...

From the page:

A Baby Language interpreter ignores the input program and does something random. (Likewise, a Baby Language compiler generates a random executable.) As such, whatever you wanted your program to do, there's an (admittedly small) chance that it will actually do it.

The intended use case for the language is to run your program repeatedly until it does what you want. Just like trying to reason with a real baby, this may take quite a while.

So the blank program, and every program for that matter, executes a random program which will therefore randomly error!


Details on TIO link

I used Esolang user Enoua5's source code which generates and executes a random brainfuck program. It's linked on the Esolang page:

An interpreter created in Python 3 by User:Enoua5: View Source

So the TIO link above takes you to Python 3 interpreter is implemented in the header and the actual (blank) code is in the (blank) code slot, which is ignored anyway!

The above interpreter is simply copied and pasted into the header; a multiline comment starting/ending in the header/footer nullifies the actual code.

includes 3 different answers, smallest first

x86-64 machine code "function", 4 bytes

("works" in all 3 modes: 16-bit, 32-bit, and 64-bit. In other modes, FE 00 is a jmp to eax or ax.)

0000000000401000 <timejump>:
  401000:       0f 31           rdtsc           # EDX:EAX = timestamp counter
  401002:       ff e0           jmp    rax      # "return" with jmp to register

This function can be called with jmp instead of call; it doesn't need you to pass it a return address on the stack. It uses the low 32 bits of the time counter as a jump target, which might or might not be the correct return address (or somewhere else useful).

The crash possibility is code-fetch from an unmapped or non-executable page, or jumping to instructions that fault (e.g. 00 00 add [rax],al), or to an illegal instruction, like a 1F or other byte somewhere in 64-bit mode, or a multi-byte illegal sequence in 16 or 32-bit mode, that will raise #UD.

RDTSC sets EDX:EAX = the number of reference cycles since power-on (i.e. the TSC = TimeStamp Counter, SO canonical Q&A about it. Note that it doesn't count core clock cycles on modern x86). The reference frequency is normally close to the CPU's sticker frequency (e.g. 4008MHz on a nominally 4GHz i7-6700k) so the low 32 bits wraps around in just over 1 second, which is close enough to random for interactive use. Or every few seconds on chips with lower "base" frequencies.

Assuming a valid return address or other jump target exists in the low 32 bits of virtual address space, we have a 1 in 2^32-1 chance of reaching it. Or higher if there are multiple useful targets to dispatch to. (Assuming TSC is uniformly distributed, and fine-grained enough that every 32-bit low half is actually possible. I think this is the case.)

In 32 and 16-bit mode, every possible address (in the same code segment) is reachable, but 64-bit mode unfortunately still splits the TSC between EDX and EAX so most of the 64-bit (or 48-bit) address space is unreachable.

On systems like MacOS where 64-bit processes normally have all their code outside the low 4GiB of address space, use 32-bit mode. Linux non-PIE executables are mapped in the low 2GiB of virtual address space so any non-library code will be reachable.


x86 32-bit machine code function, 5 bytes

0000000000401000 <inctime>:
 8049000:       0f 31                   rdtsc           # EDX:EAX = timestamp counter
 8049002:       40                      inc    eax      # EAX++
 8049003:       ce                      into            # trap if OF==1
 8049004:       c3                      ret

On most x86 CPUs, the TSC is fine-grained and really can be any value in the low half, including 231-1. So incrementing it can produce signed integer overflow, setting OF.

Also works in 16-bit mode (incrementing only AX with this machine code), but not 64-bit mode where into isn't a valid opcode.

x86-64 machine code function, 6 bytes

(same machine code works in all 3 modes, using the default operand size for the mode; 16, 32, and 32.)

divides 64-bit user input by a random number: can overflow or divide by 0.

0000000000401000 <divrandom>:                          # input in EDX and EAX
  401000:       0f c7 f1                rdrand ecx
  401003:       f7 f1                   div    ecx       # return EDX:EAX / ECX
  401005:       c3                      ret

Yup, x86 has a true RNG built in (Intel since IvyBridge, and AMD since at least Zen).

x86 division of 64-bit EDX:EAX / 32-bit ECX => 32-bit quotient and remainder faults (with a #DE exception -> SIGFPE or other OS signal) if the quotient doesn't fit in 32-bit EAX. With a small dividend, this can only happen on divisor = 0, 1 chance in 2^32.

With function input in EDX:EAX above 2^32-1, small divisors could leave a quotient larger than 2^32-1. So the chance of faulting depends on the input value. Specifically, division runs without faulting if ECX > EDX, where ECX is the random divisor and EDX is the high half of the 64-bit input.


rdrand always sets OF to 0 so we can't use 1-byte into conditionally trap on overflow. (It only sets CF = success, 0 means HW RNG temporarily exhausted).


I can't think of any "unpredictable / undefined behaviour" situation that could actually give different results on different runs, other than meltdown-style timing that depends on microarchitectural conditions.

Some old ARM and MIPS CPUs have unpredictable behaviour that depends on timing if you for example use a multiply where the destination is one of the inputs, or on MIPS I read the result of a load in the next instruction (in the load delay slot). So for example on MIPS lw $ra, ($a0) ; jr $ra (4 bytes each) might use the original return address in $ra (the link register) if the load hits in cache, otherwise it stalls and we'd return to wherever the load points.

Ruby, 9 bytes

1/rand(2)

Try it online!

C (gcc), 17 16 bytes

Random across function calls.

Saved a byte thanks to newbie!!!

f(i){i/=rand();}

Try it online!

Has a \$\frac1{\text{RAND_MAX} + 1}\$ chance of failing with Floating point exception.

Random across runs.

C (gcc), 19 bytes

f(i){i/=(int)&i%3;}

Try it online!

Bash + Unix utilities, 12 11 8 bytes

m$RANDOM

Try it online!

If $RANDOM happens to have the value 4, this will run the macro processor m4 (which exits right away on TIO because stdin is empty). If $RANDOM has any other value, you'll get an error because there's no program available via $PATH with the indicated name.


If you want pure bash, with no external utilities, then the shortest I’ve found is my first version (which is 12 bytes long):

((1/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. :)

R, 15 14 bytes

if(rexp(1)>1)a

Try it online!

R doesn't throw errors often. In particular, dividing by 0 doesn't lead to an error (1/0=Inf); nor does attempting to access an out-of-bounds entry in a vector (outputs NA with a warning). Two easy ways to get an error are: 1. an if statement gives an error if it is not fed a TRUE/FALSE value; 2. trying to access a non-existing object.

Here, if the random variate is >1, we try to access a which doesn't exist, so R throws Error: object 'a' not found. If the random variate is <1, nothing happens.


Previous version:

R, 15 bytes

if(T[rexp(1)])1

Try it online!

Here, rexp(1) generates a realization of the exponential distribution, i.e. a random value \$x\in\mathbb R_+\$.

An error is thrown with probability \$1-e^{-1}+e^{-2}\approx 0.767\$.

><>, 3 bytes

x,;

Try it online!

My first submission in ><>, very simple

><>, 5 bytes

v
x+;

Try it online!

Explanation

The pointer will be represented by a hashtag symbol. It will replace in bewteen these spaces:

v 
x + ; 

Ok, explanation start.

The instruction pointer goes down.

v*
x + ;

The step is randomized.

v
x*+ ;

Case 1: Error

v
x +*; 

It tries to pop two items, but there is nothing on the stack. Cue error.

Case 2: Exit gracefully

v
x + ;*

It loops to the right side, and ends on the semicolon.

Bash, 1/32767 chance of success, 12 bytes

exit $RANDOM

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.

Pyth, 3 bytes

-1 thanks to FryAmTheEggman.

lO2

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!

INTERCAL, 10 bytes

DO%9GIVEUP

The only way to terminate an INTERCAL program without an error is to execute a GIVE UP statement -- running off the end of the source code is a runtime error. This program uses INTERCAL's probabilistic execution feature to have a 9% chance of successfully exiting; the rest of the time, it errors out:

ICL129I PROGRAM HAS GOTTEN LOST
        ON THE WAY TO WHO KNOWS WHERE
        CORRECT SOURCE AND RESUBNIT

Lost -A, 9 bytes (Probability 1/2)

\\\\
%1-@

Try it online! Verification1

As an introduction to Lost for anyone unfamiliar, Lost is a 2-D programming language in which the start location and direction are selected at random at the beginning of the program. This source of randomness is what we use in this challenge.

We want some start locations that will cause an error and some that will not.

The program will error if it starts on the character % going right (or down). In this case it will encounter the ops %1-@ before termination. This pushes -1 and exits. Since -1 is not a valid character code this causes an error in character mode.

The program will terminate safely if it starts on the character % going left (or up). In this case it will encounter the ops %@ before termination. This does nothing and exits.

Since we have a path that errors and one that does not, all that remains is to know that every path terminates, which is guarenteed by the \\\\. So this program is valid.

We could shorten this significantly if there was not a termination requirement. The program :

%1-@

Try it online!

Either errors, terminates cleanly or loops forever, and it selects which at random with the following probabilities:


1: For verification we turn off character mode. All outputs containing negative numbers are the ones that will error in character mode.

SQL (Oracle), 3733 Bytes

SELECT 1/INSTR(UID,3) FROM DUAL;

Fails if the User Session doesn't have a 3 in it. Edit: Was using SYSDATE, but UID is shorter. Although I'm kinda sad. I liked having a function that worked in March, but not February.

PowerShell, 10 bytes

1/(random)

Try it online!

get-random returns an int between 0 and 0x7FFFFFFF so it'll eventually divide by 0. Maybe...

05AB1E, 4 bytes

Î)ΩE

Try it online!

Î        Push 0 and input, ie. [0, ""] b/c input blank
 )       Wrap total stack to an array
  Ω      Push random element of a, ie. [0, ""]
   E     For-loop in [1 .. a]

  where a is the top of the stack

Errors when "" is randomly selected & for loop is attempted on it.
Proceeds when 0 is randomly selected & for loop is attempted on it.

APL (Dyalog Unicode), 3 bytes

÷?2

Try it online!

(Requires IO←0)

Inverse of random boolean (any range including 0 would work). I expect this'll be a common technique...

÷    ⍝ Inverse
 ?2  ⍝ Random number in [0,1] 

Octave / MATLAB, 13 bytes

det(0:rand*2)

Try it online!

How it works

rand produces a random number with uniform distribution between 0 and 1. So the range 0:rand*2 may be 0 (1×1 matrix) or [0 1] (1×2 matrix). det tries to compute the determinant, which is only defined for square matrices.

Python 3, 15 14 11 bytes

-3 bytes thanks to @newbie!

1/(id(0)%3)

Try it online!

Also 11 bytes:

id(0)%3or a

Try it online!

How: The id of an object varies across different runs. Thus id(0)%3 can be 0, which causes ZeroDivisionError and NameError in the programs above respectively.

Jelly, 5 bytes

I haven't used Jelly for a long time, it's time for me to pick it up again.

2X’İX

Try it online!

Explanation

2X    Pick random from [    1,  2]
  ’   Decrement:       [    0,  1]
   İ  Reciprocal:      [  inf,  1]
    X randrange 1      [Error,  1]

Erlang (escript), 22 bytes

Just like the other answers...

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

Try it online!

brainfuck, 2 bytes

Sometimes segfaults, sometimes doesn't.

<.

Try it online!

Wolfram Language (Mathematica), 17 bytes

1/RandomInteger[]

Try it online!

Charcoal, 2 bytes

‽‽

Try it online! Link is to verbose version of code. Explanation:

 ‽  Random value (defaults to 0 or 1)
‽   Random element from implicit range

If the first random value is 1, then the implicit range is simply [0], so the random element is just 0, which does nothing (it's implicitly printed, but printing 0 has no effect).

If the first random value is 0 however, then the implicit range is []. This is an illegal input to randrange which therefore throws a ValueError.