Your task is simple. Write a program that should obviously produce an error on first glance either when compiled or run, but either doesn't or produces some other unrelated error. This is a popularity contest, so be creative.
-
11\$\begingroup\$ hmmmm.... this one is a brain teaser. +1 \$\endgroup\$– Tim SeguineMar 6, 2014 at 22:30
-
1\$\begingroup\$ Wish I could find it... there was an old PL/I example which included a statement along the lines of "if if if = then then then = else else else = if then else ..." (PL/I allowed using its keywords as variable names, and had a conditional expression similar to C's ?: that also used the if/then/else keywords...) \$\endgroup\$– keshlamMar 7, 2014 at 5:43
-
8\$\begingroup\$ I suggest the entire brainfuck language, because BF code just looks like it won't compile. \$\endgroup\$– Agi HammerthiefMar 10, 2014 at 20:21
-
\$\begingroup\$ @NigelNquande only if you're not familiar with it... ;) \$\endgroup\$– JwostyJun 13, 2014 at 18:25
80 Answers
Python
I made this mistake when I started coding in python. So, I guess its worth telling
a=b=[1,2,3]
b.append(1)
print(a[3])
It seems like it will produce IndexError: list index out of range
right?
But, It won't! actually a,b both points to the same list so whatever we do with b will change the list. So we will see 1 as output
Having said that, lets see another example:
a=b=[1,2,3]
b=[1,2,3,1]
print(a[3])
You might expect to see 1 as output. But, you won't! Here things are different. Now, after b=[1,2,3,1] , b points to a completely different list. So, the first list remain unchanged and thus we get the IndexError: list index out of range
-
\$\begingroup\$ Knowing that lists are almost always implemented using pointers, I wouldn't expect at all the second example t o work. \$\endgroup\$– H2CO3Mar 7, 2014 at 19:05
-
\$\begingroup\$ @H2CO3 Neither do I. Actually i wanted to put it inside the spoiler tag to show it as an example but NOT as another answer. But, I couldn't use spoiler tag on the code block. \$\endgroup\$– WasiMar 7, 2014 at 19:59
-
1
JavaScript
Code 1:
(function() { return { error: undeclaredVariable }; })();
Code 2:
(function() { return { error: undeclaredVariable, foo: 'bar' }; })();
It seems both should throw ReferenceError: undeclaredVariable is not defined
, but:
- The first one doesn't throw any error
- The second one throws
SyntaxError: missing ; before statement
That's because JavaScript doesn't require ;
at the end of lines, so a return
followed by line break exits function without returning following object.
Python:
@type
@type
def f(x):
return 0/0
f(0)(0)
f(anything)(object)
returns type(object)
.
People tend to forget that decoraters don't always do what they seem to do ;)
Emacs Lisp
It looks like there should be a divide by 0 error but there is not! (evals to 0)
(when (= 0 (- ? ? ))
(print "(- ? ? ) does equal zero!")
;; look! no divide by 0 error!
(/ 1 (- ? ? )))
chars in emacs lisp are written: '?{character}' so ?a in emacs lisp == 'a' in C. The bad part about this is that a ? followed by a space character is a valid way of writing ' '. This works with anywhite space character though. In the first (- ? ? ) I am doing space minus space which is 32 - 32 == 0. In the second (- ? ? ), the second whitespace character is actually the unicode char #x2001. so it is not 0
Java
No error for any input, and the curly brackets don't even match
public class ShouldFail {
public static void main(String[] args) {
String secret = "v#19!e/\u0022;}/*sd@x";
if (!secret.equals(args[0]))
throw new RuntimeException("Invalid argument");
}
System.out.println("***/// argument is valid ///***");
}
\u0022
ends the string, the rest of the program is enclosed in /* comments */
-
\$\begingroup\$ What do we learn: don't copy+paste arbitrary data into string literals (or comments, either). \$\endgroup\$ Sep 9, 2015 at 21:19
-
public static void main(String[] args) {
try{
int a[] = new int[2];
System.out.println("Accessing out of bounds :" + a[3]);
}catch(NullPointerException e){
System.out.println("But we dont catch out of bounds exceptions :" + e);
} finally {
return;
}
}
finally is always guaranteed to run
JavaScript:
function isInputValid(value) {
return +value === 0;
}
if (!isInputValid(' \n')) throw 'Invalid input';
What happens is that the
+
unary operator tries to convert the operand to a number - and for some bizarre reason, any string containing only white-space is converted to0
.
if ('Test' === new String('Test')) throw 'The strings are equal';
The
===
operator compares the references, and the primitive string'Test'
is not equal to an instance of aString
object; therefore, it doesn't throw any error.
-
\$\begingroup\$
String('Test')
isn't anString
instance , it's just'Test'
. I guess you meantnew String('Test')
\$\endgroup\$– OriolMar 13, 2014 at 1:03
C
Here's another one:
#include <stdio.h>
int main()
{
int a[2] = { 2, 6 };
int typo = 2;
/* Calculate a[1]/a[0] + typo
to save a character (code golf!), write *a instead of a[0] */
int r = a[1]/*a + tipo;
/* the above should trigger an error because I wrote tipo instead
of typo; why does it compile correctly? */
-1; /* statement with no effect, but no warning about this? */
printf("%d\n", r); /* and this even prints the correct value! */
return 0;
}
Explanation:
The
/
from the intended division and the*
from the intended pointer dereference together form the comment starter/*
. Note that inside the comment, further/*
are not parsed, so the comment continues until the end of the intended statement. Of course, due to thwe unintentionally long comment, the-0;
is no longer a separate statement, but gets part of the previous definition, to form the complete definitionint r = a[1] - 1
. Due to the carefully chosen constants, this gives the same result asa[1]/a[0] + typo
. However, when compiling using gcc with warnings on, you do get a warning of the nested/*
(and another one about the unusedtypo
variable).
Brainfuck
Of course, this varies by interpreter, but it fails to run on mine:
Author: Darkgamma (contact: darkgamma@email(dot)com)
>++++++++[<++++++++>-]<++++++++.>+++++[<+++++>-]
<++++.>+++[<+++>-]<--..+++.>+++++++++[<---------
>-]<++.>+++++++[<+++++++>-]<++++++.>+++++[<+++++
>-]<-.+++.>++[<-->-]<--.>+++[<--->-]<+.>++++++++
[<-------->-]<---.
In Brainfuck, all text (save for the eight commands) is taken as a comment. So what's at play here? The trick's in the fact that some interpreters take "@" as end-of-source and stop interpreting after that point. Doesn't work on all interpreters but stumped me on mine until I figured out what was going on.
static void Main(string[] args)
{
object foo = 10;
object bar = 10;
if (foo == bar)
throw new Exception("They're equal!");
Console.WriteLine("Why am I here? Obviously {0} == {1}, right?", foo, bar);
Console.ReadLine();
}
Output:
Why am I here? Obviously 10 == 10, right?
The == operator compares the references of the two objects, not the unboxed value. The code above would throw an exception if it was "if (foo.Equals(bar))" instead
-
\$\begingroup\$ Which language is this supposed to be? \$\endgroup\$ Sep 9, 2015 at 21:41
-
1\$\begingroup\$ @PaŭloEbermann I think JavaScript. \$\endgroup\$ Sep 24, 2015 at 19:08
T-SQL
select CustomerID
from NorthWind.dbo.Customers
where not exists (select DivideByZero=1/0
,BadConversion=convert(int,'xxx')
,InvalidParameter=left('abc',-ShipVia)
,DateOverflow=dateadd(year,9999,getdate())
,ArithmeticOverflow=cast(1e308 as tinyint)
,InvalidCursorRef=cursor_status('junk','junk')
,BadSubquery=(select top (-OrderID) EmployeeID
from NorthWind.dbo.Employees)
from NorthWind.dbo.Orders
where CustomerID=Customers.CustomerID)
This should have a lot of errors (named in the query), but because it's a subquery in an exists clause, it runs without error. Taken from http://bradsruminations.blogspot.com/2009/09/age-old-select-vs-select-1-debate.html.
JavaScript
Disturbing string to boolean conversion
booleanValue = Boolean("false");
if(!booleanValue){
throw "I threw an error!"
}
HTML/PHP
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
<form action="dummy.php" method="post">
<dl>
<dd>select months</dd>
<dt><select id="month" name="month" size="6" multiple="multiple">
<option>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
</dt>
<dd></dd>
<dt><input name="submit" id="submit" type="submit" value="submit"/>
</dl>
</form>
You can select multiple months by holding down the shift key or ctrl key. You'd expect all selected options to arrive in $_POST after hitting the submit button.
Well...
Only one, no matter how many you pick.
NO error message, neither PHP nor HTML.
select id="month" name="month" size="6" multiple="multiple"
is the problem – PHP assigns them all into the same variable, so only the last of them survives.
name="month[]" instead of name="month"
does the trick (now they become all entries in an array).
Whoops! I'm such a n00b, I thought I could just paste a url right into the source code ..
int main()
{
http://codegolf.stackexchange.com/
printf("My first C program\n");
return 0;
}
-
2
Java
public static void main(String[] args) {
http://codegolf.stackexchange.com/questions/23250/what-no-error
}
http:
is a label, the rest of the line is commented out
-
3
-
\$\begingroup\$ @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳, but without operator :) \$\endgroup\$– QwertiySep 6, 2015 at 20:16
-
\$\begingroup\$ @Qwertiy: Not sure what you are talking about. It's still the trick with comment and label. \$\endgroup\$ Sep 7, 2015 at 2:45
-
\$\begingroup\$ @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ That is a weird username... \$\endgroup\$– hyper-neutrino ♦Sep 12, 2015 at 21:27
Python
#i don't think theres a module called antigravity..../
import antigravity
There's an easter egg in python.. im not going to tell u what it does
-
-
\$\begingroup\$ I guess anyone knowing python knows that there are many modules one doesn't know. \$\endgroup\$ Sep 9, 2015 at 21:37
C
#include <stdio.h>
int g(int a) {
return a + 1;
}
int f(int a) {
g(a);
return;
}
int main() {
printf("%d\n", f(13));
}
f
has to return an int
, but returns void
. This actually is an error and undefined behaviour, but with GCC on linux, this will work, since the return value of g
will still be in place when control returns from f
. This may - however - not be the case on any system.
-
\$\begingroup\$ This looks like a bug in the compiler. \$\endgroup\$ Apr 5, 2014 at 21:27
In AppleScript
item -1 of {1,2}
→ Expected error : AppleScript error : Impossible to get item -1 of {1, 2}.
→ Actual result : 2
The negative number -1 has a special handling. This trick works even further :
item -2 of {1,2}
→ Actual result : 1
But :
item 0 of {1,2}
→ Actual result : AppleScript error : Impossible to get item 0 of {1, 2}.
AWK
This program works like cat utility in UNIX.
AWK! Run a program that works exactly like cat
Running (in shell):
awk 'AWK! Run a program that works exactly like cat' list of files (or nothing for STDIN)
Nothing in AWK is a concatentation operator, accessing unknown variables returns empty string,
!
operator when seeing nothing returns1
. Contatenation of "AWK" variable and boolean inverse of concatenation of lots of strings gives1
(think,$AWK + !($Run + $a + $program + ...)
). AWK is line based, so1
is taken as a condition incondition { code }
block. Code block is optional, and when not specified, it prints the input line.
C or C++
Based on celtschk's answer:-
int main (int argc, char *argv [])
{
return argc ["success!"];
}
(yes, I have done that in production code, mainly to ensure people had read the code)
-
\$\begingroup\$ Note to self: read other answers before posting \$\endgroup\$– SkizzJul 22, 2015 at 18:12