# What? No error? [closed]

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.

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

# Java

  public static void main(String[] args) throws Exception {
Integer a = 1, b = 1;
Integer c = 200, d = 200;
if ( a != b || c == d) {
throw new Exception("This should be thrown");
}
}


The Integers from the range of -127 .. 127 are cached so Integer.valueOf(127) == Integer.valueOf(127) is true but Integer.valueOf(128) == Integer.valueOf(128) is false.

• Actually, the VM is required to cache the small Integers, but allowed to cache also some bigger ones. So it could actually throw an exception here. Sep 9 '15 at 21:09

# JavaScript

/21 + 21     // SyntaxError in this


SyntaxError could be expected, but this expression works and even returns true.

• Could you explain why it works? Mar 5 '15 at 19:27
• (new RegExp("21 + 21 ") / SyntaxError) in this. The quotient of a regexp and object is NaN, and NaN in this is true for some reason. Mar 7 '15 at 3:52

# python

 = 3



You expect

SyntaxError: unexpected indent


SyntaxError: invalid character in identifier


Also this:

" " == " "
False


Unicode spaces

• I just tried this in python 2.7. The output is different from yours. = 3 -> SyntaxError: invalid syntax, " " == " " -> True Mar 7 '14 at 1:59
• @Vader: NO-BREAK SPACE (U+00A0) will be converted to SPACE (U+0020) on copy/paste under Windows. Mar 7 '14 at 2:03
• @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ that fixes the issue with the ==. The = 3 is still invalid syntax. I am not entirely sure what you are saying but I think you are trying to tell me that because I copied and pasted the = 3 I will not get the desired output. Mar 7 '14 at 2:07
• @Vader: I have no idea about the first one. I only comment about the 2nd one. Mar 7 '14 at 2:15
• I don't expect SyntaxError: unexpected indent just sayin'
– gcq
Mar 7 '14 at 15:13

## APL

table ← {
⍵⍴⍳×/⍵
[{(]}) ⍝ obviously a syntax error right?
}


Result:

      table 6 8
1  2  3  4  5  6  7  8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48


This does fail:

table ← {
[{(]})
⍵⍴⍳×/⍵
}


But this runs fine again:

table ← {
0:[{(]})
⍵⍴⍳×/⍵
}


APL parsing is lazy. At least in Dyalog APL. (Really!) Also, a d-fn returns the value of the first line that gets a result. ⍵⍴⍳×/⍵ always returns a value (it's not an assignment and it doesn't have a guard), so, ⍵⍴⍳×/⍵ is run and returns a value, and the second line is never even parsed, thus, no error. In the second example, the line [{(]}) is run first, so it fails. But the third example works, because it has a guard (0:), and 0 is false so it's skipped.

• obviously a syntax error Yeah, obviously! Mar 9 '14 at 18:43

# Casio Calculator

It's quite hard to count bytes/tokens in this "language" - I've given the number of keypresses required, excluding Shift, Alpha (the second shift key) and = at the end - this certainly fits into 1 byte per keypress.

Tested on the fx-85GT PLUS model, which is a standard, non-graphing, "non-programmable" scientific calculator. Other models will work.

These calculators have two possible input/output formats: MathIO, which is default, and displays expressions as they are written on paper (e.g. fractions display properly), and LineIO, which uses the more conventional method of representing expressions as a single string of characters without vertical dimension - e.g. square root is √(...), fractions are 1⎦2 (that's meant to be like an underscore with a vertical bar of equal length attached to the right, like _| but as a single character).

## Code

You'd think that this monstrosity would give many syntax errors. How to enter it:

((.!%PowerNegative-.DegreeRight (close-paren if in linear mode)%Degree

Press = to evaluate it.

What it looks like in linear mode:

((.!%^(--.°)%°


Decimal points without numbers, multiple percent signs, multiple degree signs, too many minuses, unclosed parentheses...

## Output

0°0'36"


. evaluates to 0, just as .5 is 0.5 and 5. is 5.
Parentheses are automatically closed at the end of the expression.
((.!%^(--.°) on its own evaluates to 1 - the degree symbol disappears.
Although the calculator uses different symbols for negation and subtraction, the latter can be used for both, while the first only negates. --. is just 0.
Multiple percent symbols can be used in a single number - 1%% evaluates to 0.0001.
Without the final °, the expression evaluates to 0.01.

# C

I don't belive that nobody posted this yet (sorry for archaeology):

const int main[] = {};


C use the same namespace for function names and variable names. So this will compile and link as valid executable but will return SIGSEGV at runtime.

• char main[]={0xc3}; compiles, links and executes without any error! You can actually put any valid sequence of opcodes in there, let's say we just want to return 10: char main[]={0xb8,10,0,0,0,0xc3};
– user25169
Feb 6 '15 at 15:25
• Of course. But I was to lazy to write that. Also your is platform dependent (it will work only on x86 and fail on others). My will do the same on all platforms (will fail) :D Feb 6 '15 at 16:14

# Java (java.util.regex.Pattern)

This post's effectiveness depends on how much you know about Pattern class documentation. The behavior shown below also depends on the quirks in OpenJDK's Java Class Library (JCL) implementation of Pattern class.

1. Inline flags (valid ones as shown in documentation (?idmsuxU-idmsuxU))

Pattern.compile("(?t)"); // Throws PatternSyntaxException. Nothing surprising here

Pattern.compile("(?c)"); // Compiles normally (!)


c flag was intended to be used as inline flag for CANON_EQ, but it currently has absolutely no effect, due to the way CANON_EQ is handled.

There is absolutely no reason to use this in your code.

2. Character class intersection (shown in documentation as [\p{L}&&[^\p{Lu}]] or [a-z&&[def]], i.e. nesting seems to be required from the example)

Pattern.compile("[\\p{IsAlphabetic}&&\\pM]"); // Compiled normally (!)


And the compiled Pattern also works when matching against "\u0345".

However, it is still recommended that you follow the documentation's way of writing regex.

3. Character class in \p notation (shown in documentation to specify a POSIX character class, a java.lang.Character class, or for Unicode script/block/category/binary property)

Pattern.compile("\\p{Letter}"); // Throws PatternSyntaxException. Nothing surprising here

Pattern.compile("\\p{all}"); // Both compiles normally (!)
Pattern.compile("\\p{L1}");


all and L1 are hidden names usable by \p:

• \p{all} is equivalent to (?s:.).
• \p{L1} is equivalent to [\x00-\xFF].

However, since this is not specified in the documentation, I strongly advise you against using them even if you know you can use them.

# C++

How many times have you been told to be careful to avoid index out of bounds errors with your for loops?

#include<iostream>
#include<string>
using namespace std;

int main() {
string s="text here";
for(int i=0;i<=s.size();i++)
cout<<s[i];
return 0;
}


In C++ (and most other languages), strings are just special char-arrays. In C++, a string always has a buffer of a space at the end, which isn't usually noticed because all the functions, etc. account for it. Here I am just accessing the space directly, so it just prints a space instead of crashing with and index out of bounds error.

• Well, that's rather obvious. Indeed, operator[] doesn't check bounds, unlike at() method. Even if there were no buffer of spaces, you'd not get any error (although it really looks like a UB). Mar 7 '14 at 9:31
• @Ruslan If I do i<=s.size()+1;, I get an index out of bounds (it compiles, but crashes). Also, if I reference a vector or array this way, it crashes. With those, I have to use the < operator instead.
– user10766
Mar 7 '14 at 16:31
• Ah, I guess why it doesn't crash here. It's not a buffer of space — it's a zero terminator. That's why it works so only for std::string and only for one single character above maximum. Also, you can't get an exception for operator[] because it doesn't check bounds. You can only get a segfault on "real" out of bounds problem (e.g. with an address sanitizer). Mar 7 '14 at 20:13

# PHP

Some slightly non-standard syntax here:

<html>
<body>
<p>Error?</p>
<?php

echo beach, far away in time;

?>
<p>What error??</p>


What's going on?

There's a three-per-em space after the opening <?php tag. The PHP parser treats this as part of the tag name, and therefore fails to recognise this code block as PHP. Instead it passes it straight to your web browser. Your browser doesn't understand it either, so all you see is the HTML text that surrounds it. (An ordinary non-breaking space would have worked too, but Markdown converts those to regular spaces so we need to use something different.)

# Python 2

isSorted = lambda a: all(x>y for x,y in zip(a[1:],a[:-1]))
print isSorted( [(1+3j),(1+2j,),(2+1j)] )


The surplus comma after 1+2j does not raise a syntax error, because this is Python’s way of creating a tuple with one element. But most importantly, this avoids that in isSorted complex numbers are compared and thus a TypeError is raised. This is because apart from two complex numbers you can almost compare everything in Python, including complex numbers and tuples.

• Nice one, although it only works in python2 as python3 changed the rules for comparisons. Mar 7 '14 at 18:58

# Perl

if (false) {
# Shouldn't happen
}
else {
die "Huge error";
}


In Perl, false is not a keyword, and it's parsed a bareword ("false"). As "false" is true, the program exits without any exception (die keyword). Both strict and warnings would notice this problem, which shows why using use strict; use warnings; in Perl is a good idea.

## Java

It is more convoluted than I would like, but here it goes.

package misc;

import java.io.FileWriter;

public class HelloWorld
{
public static String writeFile(String fileName)
{
try {
FileWriter fw = null;
try {
if( fileName==null ) return "bad parameter!";

fw = new FileWriter(fileName);
fw.write("Hello, World!\n");
} finally {
fw.close();
}
} catch( Exception ex ){
}

return "OK";
}

public static void main(String[] args)
{
String result = writeFile("hello.txt"); // returns OK
System.out.println(result);

result = writeFile(null); // should return "bad parameter!", right?
System.out.println(result);
}
}


The second call to writeFile should complain, right? It doesn't. Both calls return "OK".

If fileName is null, the very first thing the method does is to return an error message. So how can it return "OK"?

The return "bad parameter!"; is executed. But before returning, it has to execute the final section. At that time, fw is null. It throws a NullPointerException and, well, forgets it was supposed to return. The exception is caught and ignored. The procedure returns "OK".

• Welcome to the site! Please be sure to add a prominent header to your answers with the language you used. e.g. ## Java as I have added above. Mar 15 '14 at 0:18
• Indeed. Thanks. Mar 15 '14 at 10:39

## XML

And you thought you knew XML...

Lo§”“@¥…™¢‰–•~}ñKð}@on%L”…¢¢‡…nÈ…““–k@æ–™“„ZLa”…¢¢‡…n


copy the above in hello.xml and open with IE.

It is encoded in EBCDIC. The XML processor is supposed to detect it. It does in IE. But when you view it, it is usually displayed in UTF or latin, so it is all garbled.

• It didn't work because of characters getting lost. It is fixed. Mar 17 '14 at 13:00
• After some tests, I see it really works only with IE. And depending how you cut and paste, it might also fail. So I copied the resulting hello.xml on florian.net/puzzle/hello.xml Mar 17 '14 at 22:58

## Ruby

1 / 0.0


This does not result in a ZeroDivisionError, but in

# => Infinity


## C#

using System;
class DivideByZero
{
static int \u004F = Convert.ToInt16('\u0031');

static void Main(string[] args)
{
Console.WriteLine(1 / O);  // Divide by Zero
}
}


This code is actually dividing by O(the letter) and not 0(the number). If you know your hexadecimal ASCII characters well, then you might notice that I am setting the value of O(the letter) to '1' converted to an int16. Perhaps even weirder to some people, the output of this program is (the number): 0

## REBOL

do not run "this"


How it works:

do: execute the following code.
not: negate.
run: runs the following thing as a bash command.
"this": an illegal bash command, does nothing.

# Ruby

class Foo

def self.get_bar
self.bar
end

private

def self.bar
1 + 1
end

end

p Foo.bar


Prints 2. Yeah, Ruby just doesn't apply the private modifier to class methods if you declare them this way. If you instead do this in a class << self block it works fine.

# Clojure

  (defn check-nil [v] {:pre [nil? v]} v)

(check-nil nil)

(defn check-keyword [v] {:pre [keyword? v]} v)

(check-keyword “sdf”)


First one throwing exception but second one does not throw any exception. First one v itself is null that way it throw exception. The form should be {:pre [(nil? v)]} and {:pre [(keyword? v)]}

main=print (0/0, 1/0)


It is funny because Haskell is such a mathematical language, but this won't produce a zero-division error. Instead it outputs (NaN,Infinity). This is because division isn't defined on integer anyways, so it just assumes they are floats, which can be NaN and Infinity.

# C

#include <stdio.h>
#include <string.h>

int main(void)
{
if(1 != 0)
perror("Error?");

return 0;
}


perror() produces a message describing the last error encountered during a call to a system or library function - In the absence of an error it will print "Success". As such the output of the program is: "Error?: Success"

This isn't anything new, but still, the syntax of C/C++ in gcc has always amazed me ;-) Of course, it compiles without any errors by gcc -Wall -pedantic-errors.

#include <ctype.h>
#include <stdio.h>

int main(int argc, char* argv[]) {
char p = '!';

switch (argc) {
while (!isdigit(p))
case 1:
p += 1;
do { break;
case 2:
p = '1';
continue;
default:
p = *1[argv];
} while (false);
}

printf("%c\n", p);

return 0;
}


a[b] is just *(a+b) and cases in switch are just labels. As a bonus, continue works like break here, because the loop checks the condition before jumping. Also, it's nice trick to spell default as defau1t while using a font where 1 and l are hard to distinguish.

:-)

#include <stdio.h>

int main(void) {
if ("hello"=="hello") {
printf("Same!\n");
} else {
printf("Different!\n");
}
return 0;
}


Hint:

Oh ho! This is classic CS 101 stuff. Strings should not be compared directly, because they're pointers!

. . . except that in this case, since they're the same literal, the compiler has optimized the literals to point to the same location in memory. Hence the output: "Same!\n".

{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}

main = 0 -- just bogus value so we can compile and see if the below definitions make sense...
-- will be an error if you actually try to run this as a program.

data Complex a = Complex { realPart :: a, imagPart :: a }

instance Monad Complex where  -- to get convenience functions liftM etc..
return x = Complex x x
Complex r i >>= f = f r

instance (Monad complex, Num a) => Num (complex a) where
-- allow Complex to be used with numerical operators
fromInteger = return . fromInteger
(+) = liftM2(+)
(*) = liftM2(*)
abs = liftM abs
signum = liftM signum

instance (Monad Complex, Fractional a) => Fractional (Complex a) where
fromRational = return . fromRational
(/) = liftM2(/)


Indeed, it's normally not possible to define an effectful action such as main by simply writing = number. If you try to run main = 0 alone, it'll sure enough give an error (indeed at compile time already).
However, I made a mistake further down in the code: the Num (complex a) instance should have Complex in uppercase like everywhere else. But it's lowercase, so the compiler will interpret this as a type variable and define a Num instance not only for Complex, but for all Monad types. This includes particularly the IO monad, so all of the sudden the definition of main on top makes sense: 0 is now an acceptable value, and will simply be wrapped up and returned.

## Python

Looks like this should produce an indentation error:

def a():
print "start"
if True:
for x in range(2):
print x
if False:
print "do not print this"

a()


but it doesn't. And it prints "start" and then 0 and 1.

In fact, Python interpreter doesn't care about the size of indentation, and it is relative to the current block.

• Doesn't look like it to me; people who golf with python would easily recognize this. We often use indentation similarly to this to save characters. Mar 13 '14 at 0:15
• "Looks like this should produce an indentation error" - No, it doesn't. At least, not to me. Mar 14 '14 at 14:31
• If I paste this into an interactive python prompt, it actually complains about the wrong indent of the last line (due to the empty line before it the function definition is finished). When I put it into a file and run that, it does nothing (because a is not actually called, the call in the last line is inside the a definition). (Both with Python 2.7.6.) I guess you meant to remove the space in the last line? Sep 9 '15 at 21:17

JavaScript

var bSum = function (result, current, index, source) {
return  result + (current << ( soucre.length - index - 1))
}
[1,0,1,0,1,0].reduce (bSum,0) //42


This obviously fails with a ReferenceError: soucre is not defined right?

Nope,
because of the function expression, there is no ASI, and the ArrayLiteral becomes a Property Accesor. Since the function has no property 0. The above fails even before, throwing a
TypeError: Cannot call method 'reduce' of undefined

• What is an ASI? Mar 23 '14 at 16:11
• @celtschk Automatic Semicolon Insertion Mar 23 '14 at 16:32

Bit late on this one, but whatever.

# PHP

<?='this ';</script>is some<%echo('code');


outputs "this is some code" (at least on my system)

PHP allows <script>...</script> and <%...%> alongside <?php...?>, <?...?>, and <?=...?> for enclosing tags for reasons nobody quite understands, allows mixing of these tags in a single script (in this example, <?=...</script> for reasons nobody quite understands, and doesn't actually require a closing tag for reasons nobody quite understands. As such, this is actually two separate code segments (<?='this ';</script> and <%echo('code');), with is some just being garbage.

# C++

Two plus two is minus four.

#include <cassert>

int main() {
struct {
int two : 2;
} _;
_.two = 2;

assert(_.two + _.two == -4);

return 0;
}


Returns successfully; there is no error. http://ideone.com/eHQcJQ

This is actually quite a useful (but dangerous) feature - controlled overflow of a limited size bitfield struct member.

# JavaScript

As you've seen, using 99999.toString() gives an error, where 99999..toString() works.

Now, have a look at this code:

0322323022302343534534535043.toString()


The number here is an octal (base-8) number. The octal notation does not have decimals in JavaScript.

Javascript

a = 1
a+++1


Javascript now has a triple plus operator

• (a++)+1. Outputs a+1 // 0 then adds 1 to a. Feb 22 '15 at 13:03

# Go

package main insofaras
import "fmt" notwithstanding
func whereas main() {
fmt despiteallobjections.Println(
thetruthofthematter "Hello, world!")
}


http://golang.org/src/cmd/gc/lex.c defines some strange keywords like despiteallobjections, which are ignored by the language.