g | x | w | all
Bytes Lang Time Link
005Uiua250830T161841Zphidas
006Pip210605T224903ZDLosc
066Bespoke250125T033547ZJosiah W
005250126T145345ZJoao-3
008Retina250125T235554ZUnrelate
031Tcl250123T151150Zsergiol
029Tcl250123T151706Zsergiol
016CASIO BASIC CASIO fx9750giii250123T134214Zmadeforl
033Fortran GFortran250122T122527Zroblogic
011YASEPL240226T182138Zmadeforl
019Swift240301T162449ZmacOSist
026Lua240227T194124ZEd The &
003Vyxal 3240227T143414Zpacman25
005Rattle210607T142319Zd01
006K ngn/k230127T183717Zcoltim
nan230127T181428ZThe Thon
005Pyt230127T142215ZKip the
016Arturo230127T135113Zchunes
011Redirection220517T125641Zm90
288Minecraft Command Blocks220515T182741Zuser1003
138A0A0210605T195109Zstefvans
029Python 3220502T134235ZJoao-3
006Brachylog220426T132330ZFatalize
025Desmos220426T083650ZAiden Ch
057C220502T004307Zlittleb2
070Nim220501T154700ZQaziquza
031PostScript220501T142551Zbartysla
091Clarion220501T134217ZDylanG
010Exceptionally220428T155907ZDLosc
027Ruby220426T064955Zoeuf
015Python 3220425T143706ZTommo499
021Standard ML Moscow ML220423T180857ZLaikoni
035AsciiDots220309T151312Zpatchara
009Perl 5220119T165844ZKjetil S
018Python 3220119T162146ZAlan Bag
132KonamiCode211203T151039ZGinger
006TIBasic210624T174143ZMarcMush
103Acc!!210720T202103ZDLosc
022Python 3210606T034233Zzoomlogo
079Go210607T235854ZZombo
015Factor210605T183100Zchunes
012///210625T212703ZAviFS
021Python 3210624T231720Zschotti
012Haskell210621T151516Zlynn
012MATLAB/Octave210605T213307Zelementi
010AWK210605T202736Zcnamejj
252COBOLGNU210607T183911Zsmarnav
007J Jsoftware.com210611T210646ZRichard
010<>^v210611T155621Zastroide
nanCommodore BASIC C64/THEC64210609T150859ZShaun Be
009GNUAPL210606T102059Zrajashek
044Whitespace210610T144955ZKevin Cr
019Clojure210609T004806Zwintermu
003MathGolf210610T140657ZKevin Cr
014Excel210609T154735ZEngineer
014C gcc210605T195821Za stone
014C# Visual C# Interactive Compiler210608T130236ZLiefdeWe
010Java JDK210606T094116ZOlivier
002Vyxal210606T013213Zemanresu
012Grok210608T194458ZAaroneou
022R210605T184301ZDominic
019R210607T150721Zqwr
018Starry210608T155703ZJay Ryan
005Japt210605T181314ZShaggy
014PHP210606T161046ZDewi Mor
017Python 3210608T090601Ztrolley8
016PHP210607T234213ZMatthew
007><>210607T224816Zuser5828
029Racket210607T183203ZMLavrent
009Perl 5 p210607T145231ZXcali
020R210606T215645ZRobin Ry
019PowerShell210606T151243ZGMills
027Lua210607T132448Zval - di
051Python 3210607T125012ZOlupo
019Python 3210607T123318ZKinuTheD
012Ruby210607T121236ZG B
010Wolfram Language Mathematica210606T204747ZGreg Mar
045C clang210606T010812ZStack Ex
014Zsh math function210606T191050ZGammaFun
013Hexagony210606T174207Zje je
006BQN210606T121646Zfrasiyav
010Coconut210606T122157Zwasif
00305AB1E210606T100736Zovs
010Julia 1.0210606T094510ZMarcMush
016Zsh210606T061415Zpxeger
005x86 Machine Code210606T034627ZCody Gra
007APL Dyalog Unicode210605T235121ZAdá
006Charcoal210605T201657ZNeil
013Wolfram Language Mathematica210605T185519ZZaMoC
013Retina 0.8.2210605T201018ZNeil
012Scala210605T200742Zcubic le
016Python 2210605T192642Zxnor
123MMIX210605T185513ZNoLonger
010JavaScript Node.js210605T183534Zuser1006
062Python 3210605T181605ZLeopardL
003Jelly210605T182653Zcaird co
004Jelly210605T181838Zhyperneu
017Python 2210605T181029Zwasif

Uiua, 5 bytes

⍤.¬◿2

pad

Asserts that the opposite of the modulo is 1, errors otherwise.

Pip, 6 bytes

VkX%aa

Attempt This Online!

Explanation

    a   Command-line argument
   %    Mod 2: 0 if even, 1 if odd
 kX     Repeat the string ", " that many times
V       Eval
        If even, eval empty string (no-op); if odd, eval ", " (parse error)
     a  If there wasn't an error, autoprint the command-line argument

Bespoke, 66 bytes

STUFF I DO HATE
snow on doorstep
social platform X
an odd number N

Errors with Invalid stack argument: 0 if the input is odd.

This works by taking the input mod 2, flipping it (i.e. 0 becomes 1 and vice versa), and calling DO ROT; this is a NOP if the argument is 1 (i.e. the input is even), and this throws an error if the argument is 0 (i.e. the input is odd). Here is the same program in "mnemonic" form:

INPUT N
DO COPY
PUSH BI STACKTOP MODULO
STACKTOP F
DO ROT
OUTPUT N

, 5 chars

screenshot of code

󷺹⪡⟞%󷰿

Port of the Python answer. Try it out here!

Explanation: explanation of code (sorry, blind people)

Retina, 8 bytes

*~`.+
*\

Try it online!

Relies entirely on eval stages which do not exist in 0.8.2. Repeats a single backslash \$n\$ times, then attempts to run that as a Retina sub-program--specifically, a match stage where the entire program is a regex, which either matches \$\frac{n}{2}\$ backslashes for even \$n\$ or is syntactically invalid due to a trailing unescaped backslash for odd \$n\$. The eval ~ is wrapped in a dry run stage * to discard its own output (which is 0, unless the input is 0 in which case it's 2) and produce the verbatim input if it doesn't error, but the same can be achieved by appending a to turn the eval'd program into a replace stage that does nothing if valid instead.

Tcl, 31 bytes

puts [expr {$argv%2?[_]:$argv}]

Try it online!

Tcl, 29 bytes

proc P n {expr {$n%2?[_]:$n}}

Try it online!

CASIO BASIC (CASIO fx-9750giii), 16 bytes

?→A
A Rmdr 2⟹₁₀1E
A

NOTE: the E in the code is the ENGINEERING SYMBOL E, because that stuff is supported in casio basic

basically, it does an overflow ("Ma") error if the number is odd.

Fortran (GFortran), 33 bytes

read*,i
print*,i/(1-mod(i,2))
end

Try it online!

YASEPL, 11 bytes

=a'=b$a%@!<

explanation:

=a'=b$a%@!<              packed
=a'                      get user input and set it to A
   =b$a                  create variable B and set it to content of A
       %                 B = B mod 2
        @                if B is equal to 1, then go to point 1 (point 1 does not exist so it errors if its true)
         !<              else, print A

Swift, 19 bytes

let f={$0/(1-$0%2)}

If $0 (the implicit closure parameter) is even, $0 % 2 is 0, 1 - 0 is 1, and $0 / 1 is the original value. If $0 is odd, $0 % 2 is 1, 1 - 1 is 0, and $0 / 0 ends up calling assertionFailure(_:file:line:).

Lua, 26 bytes

Main code

print(0==n%2 and n or -m)

Try it online!

TIO Header

-- To read input
n = io.read()

Explanation

We read in our input via io.read() into a variable n.

n = io.read()

we then write a ternary statement inside of the print function to test whether n is even or odd. If n is even, we pass it over to print, otherwise we take the negation of a nil global variable to throw an error.

print (0 == n%2 and n or -m)

Note that ternary statements in Lua come in the form of (condition and true-expr or false-expr).

Vyxal 3, 3 bytes

ḃ[x

Try it Online!

If the bit parity is 0, then it just outputs the number. Otherwise it gives a "too many recursions" error

Rattle, 5 bytes

|b%[0

Try it Online!

Explanation:

|       take input
 b      add to print buffer
  %     modulo (mod 2 by default)
   [0   the first half of an if statement checking whether the answer is 0

Why this works: If the input is even, the result of % is 0 so the if statement is used. The if statement is empty however so nothing happens (and the print buffer is printed implicitly). If the input is odd, the result of % is not 0, so the interpreter will keep skipping forward looking for a closing ] which is not to be found (the language will try to close the bracket from the if statement if it's not allowed to enter the if statement), resulting in an error.

Old best:

Rattle, 8 7 bytes

|b%[1{]

Try it online!

Explanation

|            takes the user's input
 b           adds this input to a print buffer
  %          checks to see if this value is odd (mod 2 is default)
   [1 ]      if the resulting value is 1, the code in this if statement executes
     {       this is an unsupported character, so it throws an exception
             buffer gets printed implicitly if an error was not thrown

Note

Technically, this code could be reduced to 6 bytes by removing the ] from the end.

K (ngn/k), 6 bytes

(2!)0/

Try it online!

Sets up a while-loop, testing if 2! (i.e., mod by 2) returns a truthy value when run on the input/current value. If a truthy value is returned, it then attempts to calculate 0@x, which fails with a 'rank error, as atoms cannot be indexed. If (2!) returns a falsey value on the original input, nothing else is run, and the original value is returned unchanged.

Thunno (older versions only), \$ 4 \log_{256}(96) \approx \$ 3.29 bytes

2%?J

This uses a bug which was fixed in v1.1.1. ATO has v1.2.1 so it will not work there.

Explanation

Screenshots

Screenshot 1

Screenshot 2

Pyt, 5 bytes

Đ⁺2%/

Try it online!

The code tries to do \${n\over(n+1)\!\!\!\!\mod\!\! 2}\$, which throws a division-by-zero error when n is odd.

Arturo, 16 bytes

$[n][n/(n+1)%2n]

Try it

$[n][             ; a function taking an argument n
    n /           ; n divided by...
    (n + 1) % 2   ; n plus one modulo two  (error here if n is odd)
    n             ; push n
]                 ; end function, implicit return

Re:direction, 11 bytes

++>>
 +
v
<

Try it online!

The input number n is represented in the queue as n >s followed by a v. The loop in the first line removes two >s from the front of the queue (with the +s) and adds them back to the back of the queue (with the >s), exiting once less than two remain.

An odd number goes down from the second + and hits the + below it, which consumes the >s left in the queue, coming back to itself each time, until the queue is empty, at which point it produces an error.

An even number goes down from the first + with n >s in the queue, adds a v to re-create the representation of n, and then hits the <, which is ignored in output and points to itself to end the program.

Diagram of execution paths

Minecraft Command Blocks, 288 bytes

command block picture The commands in command blocks from left to right:

scoreboard objectives add n dummy
scoreboard players set n n <Input>
scoreboard players operation s n = n n
scoreboard players set 2 n 2
scoreboard players operation n n %= 2 n
execute if score n n matches 0 run tellraw @a {"score":{"name":"s","objective":"n"}}
execute if score n n matches 1 run setblock ~ ~ ~1 redstone_block
e

I didn't count the second command block which sets the input. If it's counted the total is 315 bytes plus the length of the number.

Explanation

scoreboard objectives add n dummy creates a scoreboard objective named n. Scoreboard objectives are a way to store numbers similar to variables. Each objective can have an infinite number of variables associated with it, which are accessed like <name> <objective>. So s n would refer to the variable named s in the objective n. All the variables in this program are in the objective n.

scoreboard players set n n <Input> sets n to the input.

scoreboard players operation s n = n n copies the value of n to s. This is required because scoreboard operations overwrite the original value.

scoreboard players set 2 n 2 sets the value of the variable 2 to 2. This is required because scoreboard operations can only be done with two variables, not a variable and a number.

scoreboard players operation n n %= 2 n modulos n by 2.

execute if score n n matches 0 run tellraw @a {"score":{"name":"s","objective":"n"}} prints the value of s (which was set to n) if n is 0, which indicates the number was even.

execute if score n n matches 1 run setblock ~ ~ ~1 redstone_block sets the block to the right of the command block to a redstone block if n is 1, indicating the number is odd. This triggers the last command block.

e is an invalid command, which throws an error, as seen here. error

A0A0, 161 146 138 bytes

I0A10A6V0
G-1G-1A5G0D2A0
A8O0
G1
A0A0
A0C3G1G1A0
A0L1S2M4
A0A1G-3G-3A0
G-3


G-1G-1



A0A0
C3G1G1A0C3G1G1A0
G-10A0G-10A0
A0A1G-3G-3A0
G-3

Since A0A0 does not have a modulo, or division, this uses repeated subtraction by 2 to get down to either a 0 or 1. If 1, the number is odd, if 0 the number is even.

I0  A10 A6 V0
G-1 G-1 A5 G0 D2 A0
A8  O0

Reads a number from the input I0 and distributes the operand over two other lines. A5 G0 D2 A0 completes the loop below in which we inserted the operand and A8 O0 finishes the print function.

A0  A0
A0  C3 G1  G1  A0
A0  L1 S2  M4  V0 G0 D2 A0
A0  A1 G-3 G-3 A0
G-3

With the inserted code executed before this completes a loop that compares the operand to 1 and jumps to 1 (operand is greater than 1), 0 (operand is equal to 1) or -1 (operand is less than one) lines down depending on the comparison. We add 2 to this and multiple it by 4, to get the offsets 12, 8 and 4.

A0   A0
C3   G1 G1   A0  C3 G1 G1 A0
G-10 A0 G-10 A0
A0   A1 G-3  G-3 A0
G-3

This is a loop located 12 lines down, executed when the operand is 2 or more, to jump back up to the repeated subtraction loop. It's padded with no-ops G1, since the loop must have three instructions or more to work.

At offset 8 is nothing, to stop the program.

At offset 4 is the code A6 V0 O0. The A6 is a leftover from copying, but the last two print the initial value that was entered.

Edit: forgot to mention, but A0A0 has no errors or exceptions, so this only halts.

Edit 2: Optimized by 15 bytes. I misunderstood the default loop template I make use of in the code. I was under the impression that the amount of G1 and G-3 instructions on line 2 and 4 of the loop resp. needed to match the amount of instructions inside the loop. This is not the case, you only need two of them (although more also work, as long as each line has an equal amount of them). This change removes these extra instructions.

Edit 3: Optimized by 8 bytes. Because of edit two, it turns out that there's actually no minimum of three instructions in the loop. This allows us to drop four instructions (not two, since the loop at the bottom is partially evaluated), totalling eight bytes. I've also added a link to the language page in the post, since that was not present.

Python 3, 29 bytes (full program)

a=int(input())
print(a<<a%-2)

Explanation:

a=int(input()) # usual input line
         a%-2  # even numbers map to 0, odd numbers map to -1
      a<<      # part which triggers error (can't shift negative times)
print(       ) # output if no error

Try it online!

Brachylog, 7 6 bytes

./₂ℕ∨ị

Try it online!

Explanation

Raising up an error in Brachylog is surprisingly difficult (outside of transpilation errors obviously): in general in declarative logic programming it is better for predicates to fail ("return" false) rather than to throw errors (which has side-effects). Many things that you would expect to error don’t error, they simply don’t succeed to allow backtracking.

The simplest way to raise an error I thought about is to force computation (i.e. use floating point arithmetic, not constraint integer arithmetic) of something undefined: computing ln(0).

@UnrelatedString found a 1 byte way to error: trying to cast a string to an integer, when the input string is a free variable.

.             Input = Output
 /₂           Divide it by 2
   ℕ          It must result in a non-negative integer
     ∨        If all that fails
      ị       Try to cast a free variable from string to int

Desmos, 30 29 28 25 bytes

f(n)=[1...mod(n,2)8!][1]n

A lot of stuff that I tried just gives undefined instead of erroring out, but I finally found something that worked.

Try It On Desmos!

Try It On Desmos! - Prettified

C, 57 bytes

main(c,v)char**v;{c=atoi(1[v]);printf("%d",(c%2)?0/0:c);}

Exploits the ternary conditional to divide by zero (fastest way of causing an error?) if the first argument isn't even. Also abuses the argc variable to store the number.

Note: To compile using LLVM Clang, use flag -std=c89. However, Clang-compiled versions won't just go though with attempting to divide by zero. Sad.

A longer one (works with gcc and clang):

main(c,v)char**v;{c=atoi(1[v]);printf("%d",(c%2)?v[9999]:c);}

Attempts to access memory outside the program's bounds when given an odd number. Try removing some 9s at the cost of making the likelihood of accessing memory outside the program's bounds smaller. Works with three 9s in TIO.

Yes, I know that atoi isn't exactly good, but it's nice and short.

Nim, 70 bytes

proc f(n:int)=
  if n mod 2==1:raise Exception.newException""
  echo.n

Attempt This Online!

The first solution that came to mind. Rather run-of-the-mill.

PostScript, 31 bytes

.runstdin dup 2 mod 1 eq{x}if =

Requires ghostscript for .runstdin; raises /undefined in x on odd input.

Clarion, 91 bytes

In Clarion, calling a function that is prototyped to return a parameter, but the body of said function does not explicitly return anything causes a runtime exception. I think I might be cheating slightly by not explicitly halting the program, but the dialog that shows after the exception occurs has a "Continue" or "Exit" button, and if you hit continue it will re-trigger the exception, giving you no choice but to terminate anyway.

The input is given as the first command-line parameter.

It's not particularly short compared to the other incredible answers here, but I like Clarion :)

Program
 Map;f,?.
Code
 i#=Command(1);If i#%2=0;Stop(i#);Else;x#=f().
f Function
 Code

Exceptionally, 10 bytes

GI}n%2=0Pn

Attempt This Online!

Explanation

GI}n%2=0Pn
G           Get a line of stdin
 I          Convert to integer
  }n        Store a copy of that value in n
    %2      Mod 2
      =0    Assert equal zero; if it's not, throws an error
        Pn  Otherwise, print n

If the program reaches Pn successfully, it loops back to the beginning, tries to read another line of input, and dies when there is no line to read.

Ruby, 27 bytes

n=gets.to_i;p(n%2==0?n:n/0)

Attempt This Online!

Python 3, 15 Bytes

print([n][n%2])

Standard ML (Moscow ML), 21 bytes

fun$0=0| $x=2+ $(x-2)

Defines a function $ : int -> int that throws an Out_of_memory exception for odd numbers. Requires the Moscow ML interpreter.

- fun$0=0| $x=2+ $(x-2);
> val $ = fn : int -> int
- $ 4;
> val it = 4 : int
- $ 3;
! Uncaught exception:
! Out_of_memory

Standard ML, 22 bytes

fn x=>x div(1-x mod 2)

Try it online!

Anonymous function that throws a Div exception and works in all implementations.


Just for fun, here are some other exceptions:

Match, 24 bytes

fn x=>(fn 0=>x)(x mod 2)

Try it online!

Bind, 29 bytes

fn$ =>let val 0= $mod 2in$end

Try it online!

AsciiDots,41 35 bytes

.&#$--\
*#1-*[-]/2#*.
\#?{+}*{%}[/]

Try it online!

Perl 5, 9 bytes

$_%2&&die

Try it online!

Python 3, 18 bytes

lambda n:n/(n%2<1)

Try it online!

KonamiCode, 132 bytes

>>>>(^^)v(>)>(^)v(>)L(>)>(^)v((>))>(^^)S(^)A(^^)v(^)A(^>^)L(^^)v(>)B(^^^)L(^^^)L(^>^)>(>)S((^))>(^)B(>)>(^^)S(>)A(^>)>(^>)<<L(^>)<<<

This is basically identical to my answer here, but with a bit of code on the end that causes an InvalidMemoryIndexError if the number is odd.

TI-Basic, 9 6 bytes

sum(dim(identity(Ans/2

Tries to create a Ans/2-size identity matrix, which will fail for odd numbers

It will also fails for big-ish numbers depending on the available RAM

Acc!!, 103 bytes

N
Count i while _%60/48 {
_*60+N
Count j while 10/(_%60)*(i-j+1) {
Write _/60^(i-j+1)%60/(1-_/60%2)
}
}

Dies with a division-by-zero error if the input is odd. Try it online!

Explanation

We start with a loop that reads digits into the accumulator until hitting a newline:

N
Count i while _%60/48 {
_*60+N
}

At the end of this loop, the accumulator can be read as a base-60 number whose digits are the entered characters' ASCII codes (the last one being 10 for newline). The loop variable i is one less than the number of digits in the input number. We need to know the length of the number to output the digits in order; since i goes out of scope as soon as its loop exits, we'll need to nest the output loop inside the input loop.

Naively, we could output the digits like so:

Count j while i-j+1 {
Write _/60^(i-j+1)%60
}

But we only want this loop to activate when we've just read a newline; so we multiply the condition by 10/(_%60), which is 1 when the last character read has a code of 10 (or below) and 0 when it has a code above 10:

Count j while 10/(_%60)*(i-j+1) {

Finally, we need an error when the input number is odd. This is the case if the final digit's character code (_/60%60) is odd; 1-_/60%2 will give 0 for odd and 1 for even. Then we can simply divide the output expression by this quantity to get the desired error/no-op behaviors:

Write _/60^(i-j+1)%60/(1-_/60%2)

Python 3, 31 23 22 bytes

lambda x:x&1and a or x

Try it online!

Very simple answer, if the number is odd it just tries to check the value of an undefined variable.

-8 bytes! thanks to @Wasif

-1 byte due to replacing if .. else with and..or

Go, 79 bytes

package main
import."fmt"
func main(){a:=[]int{0}
Scan(&a[0])
print(a[a[0]%2])}

Factor, 15 bytes

[ 2 / 1 shift ]

Try it online!

Thanks to @umnikos

Factor, 19 bytes

[ dup 1 + 2 mod / ]

Try it online!

Throws a divide by zero error on odd numbers, while returning even numbers.

Explanation:

Here's a slightly longer version that simply asserts the number is not odd:

[ dup odd? f assert= ]

///, 12 bytes

/??/!!//?/?/

Try it online!

The /// language is Turing complete, yet only has one command: a simple /find/replace/. No special characters except the forward and back slashes. Each /find/replace/ loops until it can no more, before moving onto the next. In ///, the input is appended to the end of the program. The link places the input in the footer.

This program uses unary to represent numbers, taking input with ? and returning output with !.

/??/!!/    Replaces all pairs of '?', with pairs of '!'
/?/?/      Replaces any '?' left with itself, creating an infinite loop

On evens, all questions are replaced with exclamations in the first pattern, and the program terminates with as many exclamations as it had questions. The same number is returned in unary.

On odds, after the first pattern there is one question mark left. This gets replaced with itself ad infinitum until TIO times out after 60 seconds.

There's technically no consensus that this counts as an error, but I'm counting TIO as the implementation here. Otherwise, I can certainly write another implementation that times out, or that uses recursion to eventually stack overflow.

Python 3, 21 bytes

lambda x:x//((x+1)%2)

Try it online!

Haskell, 12 bytes

f x|even x=x

Try it online!

MATLAB/Octave, 17 13 12 bytes

-4 bytes thanks to Sisyphus

@(x)x(i^2^x)

Try it online!
Anonymous function. Throws indexing error for odd numbers.

This function returns element from input at index i^2^x = (-1)^x, so

AWK, 11 10 bytes

1/($1%2-1)

Try it online!

Thanks to tail spark rabbit ear for helping drop one char...

Divides by zero if the number is odd, otherwise the test is truthy and the default action prints the commandline..

COBOL(GNU), 252 bytes

IDENTIFICATION DIVISION.PROGRAM-ID.A.DATA DIVISION.WORKING-STORAGE SECTION.
     01 A PIC 9(2).
     01 R PIC 9(2).
     01 Q PIC 9(2).
PROCEDURE DIVISION.ACCEPT A.DIVIDE A BY 2 GIVING R REMAINDER Q.IF Q IS EQUAL TO 0
DISPLAY A
ELSE
STOP RUN.
STOP RUN.

Please let me know if I can golf this down even more. Don't have time to explain this now.

https://tio.run/##bY4xbwIxDIX3@xUey5AI2DqaxEQWR5JzclSMLQIWBFKrSv31Tc3SY8DT82f5vXe4fdwu5nz9bo09xcprdlg5RfC846LCZklBcGvYW7QeK06ntyQbjsGUmgQDQSF3/7Ud3Ge@AITMDl5flrOJyRM2PDDNc@RHoSkHnaNcQeOVeFLb1R6WEHSLQQ2FtsjRk8Bgea1uXICGEXuoCead55J73AN21BfqtG0GGbXmv2rt93C6vJ@/mvlp5vR5PP4B

J (Jsoftware.com), 7 bytes

   f=: 13 : '(2|y){y' NB define function f
   f                  NB. display f 7 bytes 
   =============> this is the function, it is seven characters
     ] { ~ 2 | ]
   <=============
                  NB. spaces optional
                  NB. ..and shown for clarity

   f 2                NB. test with even number
2
   f 3                NB. odd number throws error
    |index error: f
    |       f 3

NB. 2|y finds n mod 2 => 1 odd or 0 even 
NB. { use result as index into input
NB. there is only one input so 1 throws error

<>^v, 10 bytes

2,tT%1=VT;
Explanation
2,tT%1=VT;

2          Push 2 to the stack
 ,         Read number from stdin
  t        Pop stack and store into variable `t` 
   T       Push the value of the variable `t` on the stack
    %      Modulo top of the stack by second element of stack
     1     Push 1
      =    Execute next instruction only if top 2 elements of the stack are equal
       V   Access variable V, which is undefined and cannot be set because its setter is a keyword (throws error)
        T  Push value of variable `t` onto stack
         ; Print top of stack

It tests if the number entered modulo 2 returns 1, if so (odd) it tries to access an undefined variable, so that throws an error and exits. If the modulo result is 0 (even), it pushes the number (stored in a variable), and then prints the top of the stack.

online link (the > is the input prompt, it is not an output of the program)

Commodore BASIC (C64/THEC64, PET, C128, VIC-20, C16/+4) - 18 14 BASIC bytes used <- invalid entries (now removed) - 25 19 17 BASIC bytes

0INPUTN:ONNAND1GOTO1:PRINTN

It takes any numeric input and logically ANDs it with 1; Therefore for every odd number, this is 1 otherwise it is 0. This value is passed to the ON...GOTO command. Where this is zero, it passes through to PRINT N and the program exits gracefully. Where this value is one, it will branch to line 1 which is not there, and therefore it reports an ?UNDEF'D STATEMENT ERROR IN 0.

The old entry did not output any valid number, and so was removed. It was something like this:

0INPUTN:N=NAND1:IFNTHENX

GNU-APL, 9 bytes

{⍵÷2⊤⍵+1}

The above function divdes the given number n with (n+1) mod 2.

Samples for 2 and 3

      {⍵÷2⊤⍵+1} 2
2
      {⍵÷2⊤⍵+1} 3
DOMAIN ERROR
λ1[1]  λ←⍵÷2⊤⍵+1

TIO in ngn/apl.

Whitespace, 44 bytes

[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S N
S _Duplicate_input][S S S T S N
_Push_2][T  S T T   _Modulo][N
T   S N
_If_0_Jump_to_Label_EVEN][N
S N
S N
_Jump_to_nonexistent_Label][N
S S N
_Create_Label_Even][T   N
S T _Print_as_integer]

Letters S (space), T (tab), and N (new-line) added as highlighting only. [..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Integer input = STDIN as integer
Integer temp = input modulo-2
If (temp == 0):
  Go to label EVEN
Go to nonexistent label (causing an error)

Label EVEN:
  Print input as integer
  (also shows an error: no exit defined; could be prevented by adding three trailing newlines)

Clojure,20 19 bytes

#(/ %(- 1(mod % 2)))

#(/ %(mod(inc %)2))

Try it online!

MathGolf, 3 bytes

¥┌/

Try it online.

Explanation:

¥    # Modulo-2 the (implicit) input-integer
 ┌   # Invert the boolean (0 becomes 1 and vice-versa)
  /  # Integer-divide the (implicit) input-integer by this
     # (which causes division by zero errors)
     # (after which the entire stack is output implicitly)

Excel, 14 bytes

=A1/ISEVEN(A1)

Input is in the cell A1. The formula can go anywhere else.

ISEVEN() is a built-in that returns TRUE or FALSE. When you perform a math operation (like dividing), Excel treats TRUE as 1 and FALSE as 0. So odd numbers will try to divide by zero and return an error.

enter image description here

C (gcc), 28 15 14 bytes

-13 thanks to Jonathan Allan
-1 thanks to Olivier Grégoire

f(a){a/=~a&1;}

Try it online!

How ~a&1 works is explained in this solution.

C# (Visual C# Interactive Compiler), 14 bytes

a=>a%2<1?a:a/0

a=>                 # Function taking a
   a%2<1            # Boolean which is true if a is even 
        ?a          # If true return a
          :a/0      # If false return a/0 which errors

Try it online!

Java (JDK), 10 bytes

n->n/=~n&1

Try it online!

Explanations

This code basically divides by zero when the input number is odd or by one when it is even.

~n

The ~ character negates each bit of n because n&1 returns 0 when n is even and 1 when it's odd, but we want the opposite: 0 when odd (to make it fail) and 1 when even to return it, so ~ is the easiest way to negate the last bit.

~n&1

This is the part that reduces n to either 0 or 1. ~n&1 is not exactly the same as ~n%2 because, in Java, %2 keeps the signum of n, and since we definitely swap the signum with ~, we'd always end up with negative number, not matter what n is: if n<0 we'd get negative divided by positive, and if n>=0, we'd get positive divided by negative.

We want to divide by 0 or by 1, nothing else. Only &1 can guarantee that. No matter what, the operator priority will first evaluate ~n so no parenthesis are required.

/=

This bit is weird. Why do we do divide and assign, instead of just dividing? Technically, n/~n&1 will be parsed as x=n/~n then x&1. This is not the behavior we want: n/~n is always equal to 0. What we want is to have n/(~n&1). It could work well, but the whole answer would be n->n/(~n&1). The /= operator is a shortcut to that as it evaluates the right-hand side entirely, so we can get rid of parenthesis, gaining one byte. Assigning is a side effect we can live with.

Vyxal, 2 bytes

₂ḭ

Try it Online!

-1 thanks to Aaron Miller

₂  # Is_even(n) (Vyxal has no booleans, only 0 and 1)
 ḭ # Integer division (ordinary division doesn't error on 0)

Grok, 12 bytes

:Y2%}_
qzp h

Try it Online!

Copies the input number, and if n%2 = 0, goes down and to the left, prints, and terminates. If n%2 = 1, then it hits _, which errors, since it is an invalid command.

R, 25 23 22 bytes

Edit: -2 bytes after looking at ophact's answer, and then -1 byte thanks to Robin Ryder

`if`((n=scan())%%2,,n)

Try it online!

Throws an 'argument is missing' error when n is odd and the if expression tries to read the missing expression that should be between the two commas.

R, 20 19 bytes

(x=scan())[[!x%%2]]

Try it online!

R 4.1, 15 14 bytes

\(x)x[[!x%%2]]

Takes advantage of the fact that an R numeric is automatically a vector.

-1 byte by using a different indexing error due to Dominic van Essen.

Starry, 18 bytes

, +       +    *'.
0,    push input
1+    duplicate
7+    push 2
4*    modulo
0'    jump to label 0 if top is non-zero
0.    print top

If the input mod 2 is non-zero (1) it attempts to jump to a label that doesn't exist, so it throws an error. Otherwise it reaches the end and prints the number.

Try it online!

Japt, 6 5 bytes

Throws a TypeError an overflow error on odd numbers. Still convinced there must be a much shorter way 🤔 /v would work if JavaScript errored on division by 0.

*v ªß

Try it

*v ªß     :Implicit input of integer
*         :Multiply by
 v        :  Divisible by 2?
   ª      :Logical OR with
    ß     :A recursive call

PHP, 14.

die($argv[0]);

There's no need to differentiate odd and even. The criteria say odd numbers can display any error, while even ones should be displayed.

Since the criteria allow for ANY error on an even number, and die() displays an error and terminates, the input is fine as an error.

The criteria allow for even numbers to be displayed in any manner, including as an error, so again, the input is fine as an error.

But if die() isn't accepted as an error, and a genuine terminating error's required... 27 26 bytes. Sadly we can't use die() here...

echo($a=$argv[1])%2?$b:$a;

If warnings are acceptable as errors, then in the comments Matthew Anderson's suggestion to use division by zero also gives us 26 bytes:

echo($a=$argv[1])/!($a%2);

Python 3, 17 bytes

lambda x:[x][x%2]

Try it online!

It's very simple - construct a list with a single (zeroth) number and take an element of it with index equal to that number modulo 2. Since there is no element 1, it will obviously throw an exception on odd input.

PHP, 16 bytes

1/!($argv[1]%2);

Divides 1 by opposite the input mod 2. Throws a division by zero error upon odd numbered inputs.

Try it online!

><>, 7 bytes

:2%?Cn;

The input should be put onto the stack using the -v command-line argument.

Try it even!
Try it odd!


Explanation:

Initially, the stack contains the input number, \$ n \$.

If \$n \% 2 \neq 0\$:

If \$n \% 2 = 0\$:

Racket, 29 bytes

(λ(x)(/ x(modulo(add1 x)2)))

Try it online!

Perl 5 -p, 9 bytes

$_%2&&die

Try it online!

R, 20 bytes

n=scan();n+(n%%2&&a)

Try it online!

The && operator is logical AND, evaluating left to right until the result is determined. If n is even then n%%2 is 0, coerced to FALSE, and the a part of the expression is therefore not evaluated. We then output n+0, ie n.

If n is odd, then n%%2 is 1, coerced to TRUE, and we need to evaluate the a part of the expression to determine the result of n%%2&&a. Since a is undefined, this produces an error.

This strategy comes out 3 bytes shorter than Dominic's strategy with if.

PowerShell, 31 25 14 19 bytes

-6 bytes thanks to @mazzy

param($n)$n/!($n%2)

Try it online!

Calculates the modulo of the input number and 2, implicitly converts the result to a boolean in order to negate it, then divides the input number by the negation. Inadvertently ditched the spec for a while there, sorry!

Lua, 27 bytes

print(...%2<1 and...or o())

Try it online!

Not very creative or tricky. Thanks to JS answer for reminding me about ternary operator.

Python 3, 51 bytes

i=input()
if int(i)&1:raise Exception
else:print(i)

Try it online

Python 3, 19 bytes

lambda x:x//(1-x%2)

If the number is even, x%2 is 0 and 1-x%2 is 1, so this evaluates to x//1 which is simply x, since floor dividing by 1 gives the original integer.
However, if it is odd, x%2 is 1, 1-x%2 is 0, and this evaluates to x//0 which raises a ZeroDivisionError.

Ruby, 12 bytes

->n{n/=1&~n}

Try it online!

Wolfram Language (Mathematica), 10 bytes

I think this uses an approach that isn't yet represented in the other answers.

–1 byte thanks to att!

#+0^I^#^2&

Try it online! Here I represents the imaginary number i. Since the square of every even number is a multiple of 4, I^#^2 equals 1 when the input is even, and so 0^I^#^2 becomes \$0^1\$ which is a perfectly nice 0 to add to the input. However, since the square of every odd number is one more than a multiple of 4, I^#^2 equals i when the input is odd, and so 0^I^#^2 becomes \$0^i\$ which throws an "Indeterminate expression " error.

first submission: 11 bytes

#+0^(-1)^#&

Try it online! Since –1 to an even power equals 1, 0^(-1)^# becomes \$0^1\$ when the input is even, which is a perfectly nice 0 to add to the input; however, since –1 to an odd power equals –1, 0^(-1)^# becomes \$0^{-1}\$ (the reciprocal of 0) when the input is odd, which throws an error.

C (clang), 74 45 bytes

main(i){scanf("%i",&i);printf("%i",i/=~i&1);}

Try it online!

Takes an int for input, then uses an if-else statement to choose if the number is odd or even. If the number's odd, it doesn't output anything, but shows the error anyway. Even numbers display the error, but at least the number is inputted.

Thanks to ceilingcat, with the help of Olivier Grégoire, for golfing 29 bytes.

Zsh (math function), 14 bytes

((1/1&~$1,$1))

Try it online!

Unlike in Bash, C and many other languages, in Zsh & binds more tightly than / by default, allowing us to get division by zero on odd numbers with just 1 / 1 & ~$1.

(Zsh does have a C_PRECEDENCES option which changes arithmetic binding to the traditional order.)

Hexagony, 13 bytes

?#\.@!:.!_@\|

Try it online!

Expanded: (Made using Hexagony Colorer)

Hexagony Colorer Map

This code is built around Hexagony's # operator. Hexagony initializes with 6 IP's, 1 in each corner of the code box, with the 0th one, the one in the top left, being active in the beginning. The # operator takes the value of the current memory cell mod 6, and then sets the corresponding IP as the active one. So making an even/odd checker is a matter of using the # operator and then having IP's 1,3, and 5 perform the 'odd' action, and IP's 0,2, and 4 perform the 'even' action. The consequence of doing it this way is that there are 6 separate paths that each need to be mapped to the correct endpoint, hence the mess of paths. In this case, the odd action is : (attempt to divide two non-existent values, resulting in a divide by zero error) and the even action is !@ (print and terminate). To make it hopefully a bit more readable, here's a very low-tech drawing of the paths:

Hand-drawn map

The paths are:

I'm pretty confident 12 bytes is possible, and potentially even shorter. Not sure if there's a better approach entirely, but with this method, it seems just about brute-force-able. It seems it should only require ?,#, no more than 3 each of @,!, and :, and some control flow characters.

BQN, 7 6 bytesSBCS

¯2⥊⍟|⊢

Try it here.

How it works:

¯2⥊⍟|⊢
  ⥊     # reshape (this can be any function that is not dyadically invertible)
   ⍟    # power modifier (𝔽⍟𝔾 applies 𝔽, 𝔾 number of times)
¯2  |⊢  # input mod ¯2, gives 0 if even, ¯1 if odd.

𝔽⍟0 is just equivalent to the identity function so it returns the input, and 𝔽⍟¯1 calls the inverse of 𝔽 1 time, but since can't be inverted it gives an error.


7 Byte solution:

⊢⊣·!2|¬

Try it here.

How it works:

⊢⊣·!2|¬
      ¬  # not (in BQN not(x) is extended to 1-x)
    2|   # mod 2
  ·!     # assert (throws an error if not 1)
⊢⊣       # return the input

Coconut, 10 bytes

n->n<<n%-2

Try it online!

Coconut port of @xnor's trick

05AB1E, 3 bytes

Èи¿

Try it online!

or

È×F

Try it online!

È checks if the input is even. Returns 1 for even numbers, 0 for odd numbers.

Julia 1.0, 11 10 bytes

n->n[~n&1]

Try it online!

Numbers can be indexed by one (4[1] == 4) but any other number will throw an error (0 here when n is odd)

-1 byte thanks to Olivier Grégoire's answer

Zsh, 16 bytes

<<<$1>0
<$[$1%2]

Try it online!

x86 Machine Code, 5 bytes

A8 01 74 01 F4

Takes the integer value of your choice in the EAX register, halts the CPU if the number is odd, or continues execution harmlessly if the number is even.

Ungolfed assembly language mnemonics:

A8 01         test   al, 1
74 01         jz     IsEven
F4            hlt
          IsEven:

The first two instructions (test+jz) are the fastest and smallest way to check whether an integer value is even or odd in x86 machine code. The reason they work is hopefully obvious: for binary numbers, the least-significant bit (bit 0) is only set if the number is odd (for even numbers, the least-significant bit is clear). Therefore, testing the least-significant bit and seeing if it is non-zero is the easiest, simplest, smallest, and fastest way to see whether a number is even.

Here, I've used jz to jump if the zero flag (ZF) is set—i.e., if the bit we tested (bit 0) was zero, which means that it jumps if the number was even. Note that it jumps over the halt (hlt) instruction if the input value was even. If the input value was odd, then execution falls through the jump, and ends up halting the CPU.

If you don't like hlt because you don't think that counts as throwing an exception/error, then replace it with an int 3 instruction, which is also only 1 byte (0xCC), and thus doesn't change the overall code size (5 bytes). The int 3 instruction is the trap to a debugger.

The only way you could really argue that this code is cheating is that it doesn't "output" that number. I'd say it does: it allows execution to continue past the point where that number was generated, which is a lot like outputting it. You don't get any output for odd inputs; you can only get output for even inputs. Besides that, I think this is allowed by many, many different agreed-upon input/output methods.


x86 Machine Code, 6 bytes (non-competing)

A division by 0 is another obvious solution, but it doesn't save any bytes. Even if you are willing to allow clobbering the input value, in order to arrange for a division by zero, you have to negate somewhere (either the original value, or the isolated LSB), and that requires an extra instruction (either XORing with 1, or a NOT), which means 2 extra bytes.

A8 01         test   al, 1
34 01         xor    al, 1
F6 F0         div    al

That's 6 bytes, and I'm not even sure that I can figure out how to justify this clobbering of the original input value as being consistent with the requirements of the challenge to "output" the value.

To avoid clobbering, there are a few different options. For example, we can stipulate that the input is taken in a different register (say, ECX). But this means that we can't use the short "implied accumulator" encoding of test and xor, so it costs us at least two bytes. (We could use not with the full register before the test to invert the bits, which is encoded in only 2 bytes, but that defeats the point, which is to avoid clobbering the input.) Or, we could push and pop the input, but that also costs two extra bytes (one for each, push and pop). Maybe I'm missing something obvious, but I'm not seeing a better solution here.

APL (Dyalog Unicode), 7 bytes (SBCS)

Anonymous tacit prefix function

⊢÷1-2|⊢

Try it online!

 the argument

÷ divided by

1- one minus

2| the division remainder when 2 divides

 the argument

Or in other words:$$x\over{1-\Big({x\over2}-\big\lfloor{x\over2}\big\rfloor}\Big)$$

Charcoal, 6 bytes

I§0#Nθ

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

I§0#N

Cyclically (i.e. modulo 2) index into the string 0# using the input as an integer, and try to cast that character into an integer. This throws a ValueError for #.

θ

Print the input.

Wolfram Language (Mathematica), 13 bytes

#/Mod[#+1,2]&

Try it online!

-1 byte from @att

Retina 0.8.2, 13 bytes

+`[13579]$
99

Try it online! Explanation: If the number is odd, simply keeps appending 9s until Retina eventually runs out of memory, or until TIO kills it, whichever is sooner.

If you want a more direct error, then for 21 bytes:

[13579]$
9999999999$*

Try it online! Explanation: Tries to append more than a 32-bit integer length of 9s to the odd input, which throws an OverflowException.

Scala, 12 bytes

i=>i/(i+1&1)

Try it online!

Python 2, 16 bytes

lambda n:n<<n%-2

Try it online!

The expression n%-2 equals 0 for even n and -1 for odd n. Bit-shifting n by 0 positions leaves it unchanged, but for -1 positions it gives an error for "negative shift count".

MMIX, 12 bytes (3 instrs)

ihateodds   PBEV  $0,0F     // if(n even) goto ret;
            LDVTS $0,$0,6   // privileged instruction
0H          POP   1,0       // ret: return n

The LDVTS tries to make whatever memory page the input points to RWX in the cache, though not in the page table (if the input is one more than a multiple of 8). This is a privileged instruction for obvious reasons.

JavaScript (Node.js), 10 bytes

n=>n%2?_:n

Try it online!

Not a very hard answer

Python 3, 62 bytes

i=int(input())
if i%2==0:
    print(i)
else:
    raise Exception('')

Try it online!

Python 3, 41 bytes thanks to @hyper-neutrino

i=int(input())
if i%2<1:print(i)
else:1/0

Try it online 2!

Python 3, 37 bytes thanks to @user

i=int(input())
if i%2:g
else:print(i)

Try it online 3!

Jelly, 3 bytes

MḂ¡

Try it online! (even) and Try it online! (odd)

How it works

M is an atom meaning "Given a list, yield the indices of that maximal elements". Now, typically, when given integer arguments to its array functions, Jelly promotes them to either a range, to digits, or just wraps it. Unfortunately, (I'm guessing due to M's age - it was one of the earliest builtins in Jelly), M doesn't do this, and throws an error as it can't iterate over an integer.

How the code actually works:

MḂ¡ - Main link. Takes N on the left
 Ḃ  - Bit; Calculate N % 2
  ¡ - Do the following a number of times equal to N % 2:
M   -   Run the M builtin on N

If the input N is even, then yields 0 and ¡ runs M on N 0 times i.e. an identity function.

If the input is odd, then yields 1 and ¡ runs M once, which is enough to error it

Jelly, 4 bytes

ḂNXo

Try it online!

Jelly, 5 bytes

%2NXo

Try it online!

Look ma, no unicode!

ḂNXo  Main Link
Ḃ     Same thing as %2. 1 if it's odd, 0 if it's even.
 N    Negate. -1 if it's odd, 0 if it's even.
  X   Random number. Errors with -1 as input, returns 0 with 0 as input.
   o  Logical OR. If the input was odd, the program's already errored. Otherwise, it's 0,
      so logical OR gives the right value, which is the input.

Unfortunately, since dividing by zero isn't actually an error in Jelly, I cannot use that. Although, it wouldn't save me any bytes: %2C:@ is the same length.

Python 2, 17 bytes

lambda n:n/(~n%2)

Try it online!

thanks to @hyper-neutrino for -4 bytes

Python 3, 24 bytes

lambda n:n%2and 1/0 or n

Try it online!