196
votes
\$\begingroup\$

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.

\$\endgroup\$
  • 11
    \$\begingroup\$ hmmmm.... this one is a brain teaser. +1 \$\endgroup\$ – Tim Seguine Mar 6 '14 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\$ – keshlam Mar 7 '14 at 5:43
  • 8
    \$\begingroup\$ I suggest the entire brainfuck language, because BF code just looks like it won't compile. \$\endgroup\$ – Agi Hammerthief Mar 10 '14 at 20:21
  • \$\begingroup\$ @NigelNquande only if you're not familiar with it... ;) \$\endgroup\$ – Jwosty Jun 13 '14 at 18:25

80 Answers 80

1
vote
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ Knowing that lists are almost always implemented using pointers, I wouldn't expect at all the second example t o work. \$\endgroup\$ – H2CO3 Mar 7 '14 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\$ – Wasi Mar 7 '14 at 19:59
  • 1
    \$\begingroup\$ -1 huh? no surprises here \$\endgroup\$ – wim Mar 12 '14 at 0:00
1
vote
\$\begingroup\$

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.

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

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

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

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

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

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 */

\$\endgroup\$
  • \$\begingroup\$ What do we learn: don't copy+paste arbitrary data into string literals (or comments, either). \$\endgroup\$ – Paŭlo Ebermann Sep 9 '15 at 21:19
  • \$\begingroup\$ How does this...? \$\endgroup\$ – HyperNeutrino Sep 12 '15 at 21:20
1
vote
\$\begingroup\$
    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

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

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 to 0.


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 a String object; therefore, it doesn't throw any error.

\$\endgroup\$
  • \$\begingroup\$ String('Test') isn't an String instance , it's just 'Test'. I guess you meant new String('Test') \$\endgroup\$ – Oriol Mar 13 '14 at 1:03
1
vote
\$\begingroup\$

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 definition int r = a[1] - 1. Due to the carefully chosen constants, this gives the same result as a[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 unused typo variable).

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

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.

\$\endgroup\$
1
vote
\$\begingroup\$
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

\$\endgroup\$
  • \$\begingroup\$ Which language is this supposed to be? \$\endgroup\$ – Paŭlo Ebermann Sep 9 '15 at 21:41
  • 1
    \$\begingroup\$ @PaŭloEbermann I think JavaScript. \$\endgroup\$ – ASCIIThenANSI Sep 24 '15 at 19:08
1
vote
\$\begingroup\$

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.

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

JavaScript

Disturbing string to boolean conversion

booleanValue = Boolean("false");
if(!booleanValue){
    throw "I threw an error!"
}
\$\endgroup\$
1
vote
\$\begingroup\$

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

\$\endgroup\$
0
votes
\$\begingroup\$

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;
}
\$\endgroup\$
0
votes
\$\begingroup\$

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

\$\endgroup\$
0
votes
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ Who can figure it out first? \$\endgroup\$ – Maltysen Apr 4 '14 at 2:07
  • \$\begingroup\$ I guess anyone knowing python knows that there are many modules one doesn't know. \$\endgroup\$ – Paŭlo Ebermann Sep 9 '15 at 21:37
0
votes
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ This looks like a bug in the compiler. \$\endgroup\$ – Nicolas Barbulesco Apr 5 '14 at 21:27
0
votes
\$\begingroup\$

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

\$\endgroup\$
0
votes
\$\begingroup\$

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 returns 1. Contatenation of "AWK" variable and boolean inverse of concatenation of lots of strings gives 1 (think, $AWK + !($Run + $a + $program + ...)). AWK is line based, so 1 is taken as a condition in condition { code } block. Code block is optional, and when not specified, it prints the input line.

\$\endgroup\$
0
votes
\$\begingroup\$

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)

\$\endgroup\$
  • \$\begingroup\$ Note to self: read other answers before posting \$\endgroup\$ – Skizz Jul 22 '15 at 18:12

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