text:
Don't google "google"
We all know that if you google the word "google" it will break the internet.
Your task is to create a function that accepts one string and returns its length, in the fewest possible Unicode characters.
However, if the given string is google (lowercase), it will cause an error.
For example, g('bing') will return 4 but g('google') will cause an error.
Please provide an example of usage, and the error if possible.

I googled google, and Google found Google on Google. Myth Busted.

@Geobits That is simply a test to see if I will google Google, which I will not. :D

Does it have to be a function? Some languages like rs only support complete programs.

@kirbyfan64sos An equivalent would be fine in that case

This conversation has been moved to chat.

Is no output when google is entered valid, or does it have to give some kind of error?

@ASCIIThenANSI It needs to cause an error. If no output is technically an error would depend on your code.

Does the function need to be case sensitive? Should it throw given 'gOOgle'?

When I type google into google (the search bar on chrome), a message came up asking if I wanted to go to https://google/. (Now that it is a tld, this makes sense i.e. https://com.google works). I clicked it and got a dns lookup error. Internet:broken!

@AXMIM lower-case: google

Oracle: 53 bytes: select length(:x)/decode(:x,'google',0,1) from dual;

@ThomasKwa courtesy of the meta-effect and the Hot Network Questions side bar (kudos to devs, it has been a fantastic way of increasing participation)

Why is there a close vote? "Too broad"? Other than the case sensitivity, which seems like a red herring (the question says "google" in lower-case), it looks fine.

Unusually many querie on Google for "Google" in last few days.. it's tangetially related to everybody Googling for "Malamanteau".

I can't answer but here's my beginners prolog: g(S,L):-S\=google,string_length(S,L). g(S,L):-throw(S). - 56 chars, including the \n.

Does it matter what error is thrown?

What if your language ignores any errors?

@JackBates Improvise! :)

@rybo111 Any suggestions? I'm not sure what you mean by improvise.

@JackBates Some of the better answers on this site are the ones that find loopholes. For example, "cause an error" doesn't strictly mean "displays an error". Your function not returning a count is technically an error in of itself.

Thanks for the clarification! Also I can't tell if that's an insult or not?

Google

I'm voting to close this as unclear because it is not clear what an error means in the context of this question.

(related meta.)

@user202729 I'm open to edit suggestions. That's more constructive than voting to close what has proved to be a popular question IMO.

Probably "print more bytes to STDERR than Hello World program, content printed by compiler doesn't count"?

@user202729 Since the function is supposed to "break", how about "if the given string is google it will not return its length." It doesn't matter how the unexpected behaviour is handled.

Sounds good. So "do whatever except returning its length".

@user202729 My concerns are that such an edit might invalidate an existing answer, or sway the difficulty of the challenge. It's unfortunate that this wasn't raised when first posted. I'll give it some thought.

I'm voting to reopen this. I have seen no questions about what constitutes an error for this challenge and it already has 154 answers so I don't think it's fair to change the spec. This may not be an example of a good question but it's clear enough. If an answer really comes down to whether or not a certain output is an error it probably just won't get as many upvotes, anyway.

Python 2, 29
lambda x:len(x)/(x!='google')

Gives a ZeroDivisionError on "google", and the length otherwise. This takes advantage of Python's booleans equaling 0 and 1.

+1. You need to set g to your lambda, or call it anonymously with an input, though.

Just for fun, I tried this technique with JavaScript ES6. It ended up at 25, but returns Infinity for "google" instead of throwing an error...

@ZachGates The consensus on meta is that anonymous functions are allowed unless specifically disallowed. Since the question does seem to imply something like this (but doesn't explicitly disallow it, yet), you should ask the OP about it.

@Kevin you would need a return if you used def

It's anonymous if you don't set it to anything (a def is not). A lambda like this has to be called at creation. @Kevin

Amusingly, this translated to Pyth does better than my prior best Pyth solution. It is L/lbnb"google, 13 bytes.

Nice one, exactly what I was thinking as soon as I saw this question :)

Excel, 23 characters
Paste this into a cell other than A1 and type your search query into A1.
=LEN(A1)/(A1<>"google")

For example:

What's the general consensus on using Excel?

@BetaDecay.  Creative, uncommon, seems to work.  Won't be applicable to all CG puzzles, but it is here!

Managers love it!

So Efficient, CG Users Will Hate You For It. But Wait. B3 Will Change Your Life Forever!

What's the specific concensus on using Excel?

This is certainly not the first time I've used it.  I figure there's MB of libraries behind any other language used here, so this is no different.  The "source code" is the code typed in cells required to meet the criteria.  If code is typed in multiple cells, I count another byte per cell as a separator (like semi-colon or new-line.) If a challenge required "output for 1 to 100", copying and pasting the code into 100 cells and using the ROW() command as a counter variable is reasonable.  Excel has poor recursion and variable handling so is rarely a good choice for challenges.

If the formula is typed into file 'google.csv' and you open The file with Excel, …

C#, 43 bytes
An improvement over Salah Alami's answer. Recurses to throw a stack overflow exception on providing "google"
int g(string s)=>s!="google"?s.Length:g(s);

Yeah I thought that was a pretty clever way to save some characters to throw an exception. At 4 characters, it might be the smallest way to throw an exception in C#, not sure.

This is clever! However, recent versions of C# have support for tail recursion so this function will never throw StackOverflowException. In fact it will never return (behaves as while(true){}).

@NightElfik interesting! Running in LinqPad I get the message Query ended because an uncatchable exception was thrown, and in VS2015 I do get an SOException but I can't catch it when i wrap in a try-catch. Very interesting, thanks for the info! It still crashes the process though, which means it still kind of behaves like an exception, just an uncatchable one. Here's a screenshot of my test code http://i.imgur.com/xVq8cI5.png

@DLeh Tail recursion calls are little bit tricky. You have to run on x64 JIT and without debugger (debugger attached will cause tail recursion to not work for obvious reasons). Here is my program as a proof: http://imgur.com/ErNl8LJ and little more reading about tail recursion:  http://blogs.msdn.com/b/davbr/archive/2007/06/20/tail-call-jit-conditions.aspx ;)

Haha: g(string)... I'll see myself out...

@DLeh after battling for a while I think you are right..  the closest I can get is 44 bytes by causing division by zero like so int g(string s)=>s.Length/(s=="google"?0:1);

or 45 bytes causing a null reference exception int g(string s)=>(s=="google"?null:s).Length;

@lee yeah but that's longer :)

@DLeh oh wait no I can match your 43 bytes but not beat it. :) int g(string s)=>s!="google"?s.Length:s[9];

Pyth, 14 13 characters
L/lbnb"google

Defines a named function y.
This divides the length by 1 if the string is not google and by 0 otherwise. The idea is not novel, but I came up with it independently.
Try it online.
How it works
L                 Define y(b):
  lb                Compute len(b).
    nb"google       Compute (b != "google").
 /                  Set _ = len(b) / (b != "google").
                  Return _. (implicit)

Yeah I'm actually unsure about this, I don't think it's happened before with a string. Normally you could close it with ; but obviously you can't here...

You don't need the end quote.

@Maltysen I think I do. The function definition wouldn't be complete without it.

But it is complete. merely unusable ;)

"Defines a named function y." But there's no y in your code!?

@A.L That's correct. The built-in L redefines the function y.

I'm not sure, but I think I hate Pyth.

@MrLister Yes. Implicit commands. .__.

I can't find this Pyth language on the Intartubes.

@Prof.Falken Just click the Pyth link at the top of the online interpreter.

@Dennis. I see. Well, I guess Pyth could  get extended to add an operator to solve https://codegolf.stackexchange.com/questions/58891/dont-google-google ...

I don't get any output when trying the link. Also, you don't seem to need the closing "

@FelixDombek The code is interpreted on the server side, which could fail for a lot of reasons. It's working fine for me. (You're the third person to suggest that I can remove the ". I'm not sure why I'm fighting this.)

@Dennis ah, my bad, I thought I needed to put the test string in the "input" field

@FelixDombek I've edited the permalink. Input now comes from Input.

len(b)/(b != google) : utterly awesome (possibly not the originator in this answer, but the first I've read)

MATLAB, 63 41 40 38 36 bytes
Thanks to Tom Carpenter for shaving off 1 byte!
Thanks to Stewie Griffin for shaving off 2 bytes!
@(x)nnz(x(+~strcmp('google',x):end))

Unlike the other more elegant solutions, performing a division by zero operation in MATLAB will not give an error, but rather Inf.  This solution finds the length of the string by nnz.  The string that is produced is in such a way that you index from the beginning of the string to the end, which is essentially a copy of the string.  However, what is important is that the beginning of where to access the string is produced by checking whether or not the input is equal to 'google'.  If it isn't, this produces a beginning index of 1 and we index into the string normally... as MATLAB starts indexing at 1.  Should it be equal, the index produced is 0 and MATLAB will throw an indexing error stating that the index needs to be a positive integer.  The extra + is to ensure that the output of the equality check is numerical rather than Boolean/logical.  Omitting the + will produce a warning, but because this challenge's specifications doesn't allow for warnings, the + is required... thus completing the code.
Example uses
>> f=@(x)nnz(x(+~strcmp('google',x):end)) %// Declare anonymous function

f =

    @(x)nnz(x(+~strcmp('google',x):end))

>> f('bing')

ans =

     4

>> f('google')
Subscript indices must either be real positive integers or logicals.

Error in @(x)nnz(x(+~strcmp('google',x):end))

A more fun version, 83 77 76 74 72 bytes
Thanks to Tom Carpenter for shaving off 1 byte!
Thanks to Stewie Griffin for shaving off 2 bytes!
@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end');

The above isn't an official submission, but it's something that's a bit more fun to run.  Abusing eval within anonymous functions, what the code does is that it checks to see if the input string is equal to 'google'... and if it is, this will open up MATLAB's built-in web browser and shows Google's 404 error page trying to access the subpage located at i when that doesn't exist.  If not, we display the length of the string normally.
Example uses
>> f=@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end'); %// Declare anonymous function
>> f('bing')

ans =

     4

>> f('google')
>>

The last call using 'google' gives us this screen:

You could save a byte by using strcmp instead of isequal.

@TomCarpenter - Funny.  I actually told myself to use strcmp but ended up using isequal for some reason.... thanks!

nnz is two bytes shorter than numel.  You had my vote a few years ago :-)

JavaScript ES6, 34 27 25 characters
f=>f=='google'?Δ:f.length

Throws a ReferenceError on Δ for google.

alert((f=>f=='google'?Δ:f.length)('test'))

You could use a ternary operator to save two bytes.

Yay, that's exactly what I just got. If you want to be fancy, use a symbol people never use instead of g to be sure it won't exist as a global variable. Δ makes for a good variable name :)

Δ = "google is evil"; besides, I believe that these programs are self-contained.

I would use Δ but it is 2 bytes :(

@Jonathan The question wants you to count "unicode characters", so I guess it's not talking about bytes, but code points. :)

You could use #, it errors in JS afaik

Δ Google Illuminati confirmed

f=>f!='google'||f.length (not an error, but false...)

I'm just going to leave this here https://github.com/Rabrennie/anything.js/

TI-BASIC, 15 bytes
Heck, while we're at it, might as well get a TI-BASIC answer in here.
Input format is "string":prgmNAME. Credit to Thomas Kwa for finding it first!
length(Ans)+log(Ans≠"GOOGLE

(Guide: add 1 byte for each lowercase letter replacing an upper-case one. So s/GOOGLE/google/g => +6 bytes.)
ahhhhh test cases!
"GOGGLE":prgmG
               6
"BING":prgmG
               4
"GOOGLE":prgmG
           Error

20 bytes: length(Ans)/(Ans≠"google. You also have the case wrong; if uppercase is allowed it's 14 bytes. By the way, it's valid to pass arguments
through Ans.

AGOOGLE should give 7, correct? And you shouldn't be counting the program header in your code size, so subtract 10 bytes.

ERROR: I was thinking substrings. Kindly forgive me.

@ThomasKwa I didn't see your comment with the code. It just so happens that we both stumbled upon the same solution. However, if you believe you deserve the credit, the credit shall be yours. ^_^ (EDIT If you would read the code, it isn't the exact same thing.)

@lirtosiast length( is two bytes, that would make your numbers 21 and 15 bytes.

@Timtech My mistake; Conor corrected me anyway.

Python 3, 30 bytes
lambda u:[len][u=='google'](u)

Indexes the 1-element function list, raising an IndexError if the u=='google' predicate is True (= 1). Such functional.
Much variants. Wow:
lambda u:[len(u)][u=='google']
lambda u:len([u][u=='google'])

If the challenge was inverted (error on everything not "google"), could save a char:
lambda u:{'google':len}[u](u)

But you already know the length, so just hardcode it.

works for python 2.7 too

For some reason, I love this solution.

APL (14)
(⍴÷'google'∘≢)

Explanation:

⍴: length
÷: divided by
'google'∘≢: argument is not equal to 'google'.

⍴ gives the length of the string, which is divided by 1 if the string does not equal google (which gives the length back unchanged), or by 0 if the string does equal google (giving an error).

I think you don't need to count the parens, as it can be assigned to a variable without them.

Kind-of fails on single-char arguments. Fix by replacing ⍴ with ≢. Also, you can make it cooler-looking by swapping the operands of ∘. Oh, don't forget to remove the parens. All-in-all: ≢÷≢∘'google'

Haskell, 24 bytes
g s|s/="google"=length s
Output:
Main> g "google"

Program error: pattern match failure: g "google"

Main> g "bing"
4

Octave, 63 bytes
I know it is longer than the Matlab solution (which would work in Octave too), but it is particularly evil. I am making an anonymous function (evil) using cell array (evil) literals (evil) containing function handles dependent on a callback function (itself, thus recursive, evil) that must be passed via argument. Then I create another anonymous that basically reduces the function to the string argument and fixes the second argument of f as f (very evil). Any sane human would never do this, because it is almost as unreadable as Perl or regex (or cjam/pyth/any other esolang).
So if the string is not 'google' the second argument of the cell array will be called which outputs the length of the string. Otherwise the first function will be called, which is passed as a callback (and passes itself as callback to itself too) which later is the function itself. The error is basically some maximum recursion depth error.
f=@(s,f){@()f(s,f),numel(s)}{2-strcmp(s,'google')}();@(s)f(s,f)

Those things are not evil in most languages.  And this is code golf, some of the most unreadable code on the planet exists here :).  Cool handle btw.

I'm only missing some eval here to make it really EVIL :-)

CJam, 16 characters
{_,\"google"=!/}

This divides the length by 1 if the string is not google and by 0 otherwise. The idea is not novel, but I came up with it independently.
Try it online.
How it works
_                 Push a copy of the string on the stack.
 ,                Compute the length of the copy.
  \               Swap the length and the original string.
   "google"=      Push 1 if the string is "google", 0 otherwise.
            !     Apply logical NOT. Maps 1 to 0 and 0 to 1.
             /    Divide the length by the Boolean.

Interestingly enough, a full program is shorter (15 bytes): q_,\"google"=!/. Developed it before seeing this post. Note that this takes the whole input (which you seem to take anyways as a function argument). Unfortunately, you can't use it, since this asks for a function :(

APL, 19 17 bytes
{⍵≡'google':⍟⋄≢⍵}

This is an unnamed monadic function that will throw a syntax error if the input is google. This is accomplished by attempting to take the natural logarithm of nothing.
{
 ⍵≡'google':          ⍝ If the right argument is "google"...
            ⍟⋄        ⍝ Compute log(<nothing>), which brings only sadness
              ≢⍵      ⍝ Otherwise compute the length
}

Try it online
Saved two bytes thanks to Dennis!

⍟ is known informally as "splat". A very appropriate name for this usage.

JavaScript, 25 Bytes
Nice and simple JavaScript example:
e=>e!='google'?e.length:g

If "google" is entered then it passes a ReferenceError
Example

alert((e=>e!='google'?e.length:g)('test'))

Wow, thanks for telling me there's a shorthand for lamda functions in javascript!

@TomášZato Caveat: they're brand new in ES2015, so support still varies.

R, 46 bytes
g=function(x)ifelse(x!="google",nchar(x),)

Unless I'm misreading, the original post never specified that the code had to be correct syntax.
Example:
> g("bing")
[1] 4
> g("google")
Error in ifelse(x != "google", nchar(x), ) :
  argument "no" is missing, with no default

I never added anything for the "no" parameter of the ifelse statement so it will return an error if this parameter is evoked.

Here is a slightly shorter one: g=function(x)nchar(x)[[x!="google"]]

Perl, 31 29 bytes
sub{$_=pop;y///c/!/^google$/}

-2b thanks to manatwork
Usage:
sub{$_=pop;y///c/!/^google$/}->("google")

If I could get away with a program rather than a function, the following would be valid with only 20 bytes (+1 byte command line)
$_=y///c/!/^google$/

Error is division by zero.
Explanation:
y///c returns the length, then !/^google$/ will return 0 iff input matches 'google'.
Usage:
perl -p entry.pl input.txt

You could make it an anonymous function: sub{…}. (Then you call it like sub{…}->("google").)

Save 1 byte by using $_!=google instead of !/^google$/

@GabrielBenamy I'm afraid != won't work to compare string...

Java 7:53 52 Bytes
int g(String _){return"google"==_?0/0:_.length();}

Above code will throw ArithmeticException for division by zero and for any String other than google. Worth to note that == compares reference and won't work for String Objects.
Java 8 : 29 Bytes
(Based on suggestion given in below comment)
s->s=="google"?0/0:s.length()

You can also use Java 8's lambda declaration: s->(s.equals("google")?null:s).length();

"Worth to note that == compares reference and won't work for String Objects." Actually, all strings are objects, so comparing strings with == in Java will generally not work (unless you're relying on string interning, which is, well, bad). Perhaps you got confused with JavaScript?

@gengkev If they are both litterals, it will work since it is the same object that's referenced to on the String pool. The spec gives a litteral and here it is a litteral so it will work.

@YassinHajaj I agree that the spec gives it as a literal, but that's just an example. The function should probably perform the same if given input from stdin as well, or if the function is called from another class that's compiled separately. In any case, relying on compiler optimizations (string interning) is a poor idea, which is what I originally said.

Haskell - 30 characters
g"google"=error"!";g s=length s

>g "google"
 *Exception: !
>g "str"
 3

Why the exclamation mark for error? Wouldn't an empty string do too?

I wanted to suggest to change it to x=x;g"google"=x;g s=length s, but for some reason, <> exceptions aren't thrown in ghci.

g s|s/="google"=length s avoids the need for error

Python 3, 35 bytes
lambda n:len(n)if n!='google'else d

@FryAmTheEggman actually 16 bits shorter. XD

@FryAmTheEggman: Good trick but id does not work with empty string: (lambda n:len(n)*(n!='google')or d)('')

@pabouk Quite right, thanks for pointing that out.

C++11, 54 (code) + 14 (#include) = 68
Well, division by zero is just undefined behaviour, which I would not call an error. So my approach.
#include<ios>
[](std::string s){return s!="google"?s.size():throw;};

usage
[](std::string s){return s!="google"?s.size():throw;}("google");

You can call size() to save 2 bytes. In C++14, you could also use generic lambdas and replace std::string by auto. You'd need to pass an actual std::string to it instead of a const char*.

@isanae I didn't know std::string has size() method, thanks for that. I am aware of generic lambdas in C++14, but I don't know how it would help me, since "string" is const char* and not std::string.

@Zereges std::string has size() and length() because it's both a container and a string. As for auto, you'd call the lambda with (std::string("google")) instead of ("google"). The question only says "accepts 1 string" without specifying what a "string" is.

@isanae C++14 also has "google"s to construct an std::string :)

@Zereges you can simply throw; to trigger std::terminate() (because there's no current exception here).

@Quentin Ah, I didn't know about ""s being a std::string in C++14, but I wont change that since I alredy marked my answer as C++11. throw; is betten, thanks.

If you're willing to change to C++14, you could do this: [](auto s){return s=="google"?throw:s.size();};, (47 bytes) called with ("some_string"s) as @Quentin pointed out. No include needed

I really want to make a C++ dialect where every std header is #included, and using namespace std; is presumed prefixed.  One could go further (shorten class, struct, int main, template, typename etc), but that minimal boilerplate makes code that is perfectly understandable C++.

@Yakk I noticed that, but I already stated, that this is C++11. Feel free to make C++14 answer yourself with that code :)

Ruby, 29 bytes
I first came up with something very similar to @Borsunho's first attempt, but mine was slightly longer and he posted his before I was done. Came up with this before his 30 bytes edit :)
->s{s[/^(?!google$).*/].size}

Usage examples:
$ irb
2.2.1 :001 > f = ->s{s[/^(?!google$).*/].size}
 => #<Proc:0x007fa0ea03eb60@(irb):1 (lambda)>
2.2.1 :002 > f[""]
 => 0
2.2.1 :003 > f["bing"]
 => 4
2.2.1 :004 > f["google"]
NoMethodError: undefined method `size' for nil:NilClass
  from (irb):1:in `block in irb_binding'
  from (irb):4:in `[]'
  from (irb):4
  from /Users/daniel/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'

edit: Two years and some Ruby versions later

Ruby, 25 bytes
->s{+s[/^(?!google$).*/]}

Replaced String#size with the new unary plus. Try it online!

Neat, I couldn't get this to work ( I didn't came up with leaving ^ outside the matchgroup).

@Borsunho I have to admit I just "brute forced" the regex untill I got the result that I wanted :) I think the .* at the end is what makes it work.

Breaks if the input string has multiple lines and contains google on its own line. I think /\A(?!google\Z).*/m fixes it (at the cost of three bytes, though). ^ and $ match the beginning and end of lines, while \A and \Z match the beginning and end of the string as a whole.

@histocrat but I don't think you can google strings with multiple lines ;)

C, 66 48
Original:
int l(long*s){return strlen(s)/((*s&~(-1L<<56))!=0x656c676f6f67);}

Using OSX gcc,
l("duck"); returns 4,
l("google"); causes Floating point exception: 8.
On other platforms, the constants may need to be adjusted for endianness.
Shorter:
less trickyness, same results.
 l(int*s){return strlen(s)/!!strcmp(s,"Google");}

Wow, that is some interesting logic there. If I understand the golfy part right, you are somehow shifting the first six chars to fit into a single, giant number (almost like a hash), which, because of the stack being little-endian, ends up being "google", but backwards (0x656c676f6f67 = elgoog). I think this answer needs an explanation for those of us who appreciate this kind of crazy low-level stuff.

You basically have it.  It simply casts the memory storing the string into a  64 bit number.  Endianness makes it 'backward'  on  x86  architectures.  The  text only occupies 7 bytes,  so the mask just hides whatever may be next in memory.    Its a fun trick,  but I think '!!strcmp(s,"google")'  is  actually shorter.

Anyways, +1. Definitely. Also, I think you can shorten it by removing the int , that's 4 characters.

After some typing, I figured it out! If char *, with units of 8-bits, is casted to long *, with units of 64-bits, without being properly reallocated, the data in those 8 bytes of heap space becomes corrupted, and treated as a single number (8*8 = 64). That's why you get the first 6 chars, + NUL + garbage. That is very clever. Dangerous, too. Wonder why it doesn't segfault. That 8th garbage byte is out of bounds, no?

I looked at your analysis.   You are correct, the shift should have been 56, not 54.  Also, I wouldn't use the word corrupted.  The memory is the same, the bits are just interpreted differently.  Technically, accessing the garbage byte is undefined behavior, and could actually segfault.  Practically, that byte almost certainly resides in the same legal memory block as the rest of the string, and generally these blocks (heap, stack, constants) are allocated in word sized units at a minimum.  So the memory belongs to the program, it just contains something  other than the string.

The !! to reduce the strcmp to 1 or 0 is quite clever. Beat my solution by 3 bytes :) +1

42 bytes as a preprocessor directive: -Dl(s)=(strlen(s)/!!strcmp((s),"Google")).

MUMPS, 28 bytes
g(s) q $S(s'="google":$L(s))

Usage:
>w $$g^MYROUTINE("bing")
4
>w $$g^MYROUTINE("google")

<SELECT>g^MYROUTINE

Why? Well, $S[ELECT] is basically a compact multi-clause if-else statement - almost like a pattern-match in a language like Haskell or Rust. Except... unlike in Haskell or Rust, the patterns aren't checked for exhaustiveness, because the notion of "compile-time safety" is completely alien to MUMPS. So if your input is a pattern you didn't account for, you get a lovely runtime error called <SELECT>.

JavaScript, 47 bytes
Nice and simple.
Edit: Now complies with the rules
function f(g){if(g=="google")a;return g.length}

Testing
Error thrown

function f(g){if(g=="google")a;return g.length}

alert(f("Hello"))
alert(f("google"))
alert(f("hi"))

No error thrown

function f(g){if(g=="google")a;return g.length}

alert(f("Hello"))
alert(f("bing"))
alert(f("hi"))

Technically, this doesn't meet the OP's specs. This function alerts the length but returns undefined.

@Bungle How's it now?

Still the same. JavaScript functions return undefined unless you use the return keyword to explicitly return a value. You can see this by opening a browser console and declaring and executing your function. It will alert the string length but then return undefined in the console. Something like function f(g){if(g=="google")a;return g.length} would satisfy the specs and wouldn't add any bytes.

@Bungle I see. I forgot that a return was needed

Using ES6's arrow functions and ternary operator (instead of if), you can squeeze that a bit more :)

@CarlesAlcolea If I did that, it would be pretty much a duplicate of another answer :P

@BetaDecay Originality first; I respect that.

Windows Batch, 118 characters
IF /I "%string%"=="google" exit
echo %string%> string.txt
for %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 )

Output is %stringlength%.
Full code:
@echo off
del string.txt
cls
echo Type your string
echo.
set /p string=String:
IF /I "%string%"=="google" goto err
echo %string%> string.txt
for %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 )
cls
echo %stringlength%
pause
del string.txt
:err
color c
echo There seems to be an error with your input...
pause>nul

Modified from Joshua Honig's answer, here.

Ruby, 34 30 27 26
->x{x=='google'?t: x.size}

Unknown t raises exception.
->x{x=='google'?fail():x.size}

Edit: totally readable and obvious version that is shorter...
->x{x[x=~/^(?!google$)/..-1].size}

Old: Pretty similar to other ideas it seems. Will raise ArgumentError if x is 'google'.

Why those parenthesis? x=='google'?t: x.size

C - 99 75 67 63 bytes
g(char*s){int i=0,j=*s;while(s[i])j^=s[++i];return j^9?i:g(s);}

Ungolfed:
int g(char *s){
    int i = 0,
        j = s[0]; // first char of s
    while(s[i] != '\0'){
        j ^= s[++i]; // j = j XOR [next char]
    }
    if(j != 9){ // g^o^o^g^l^e = 9
        return i;
    } else {
        g(s); // infinite recursion
    }
}

Using it:
g("bing")       // 4
g("duckduckgo") // 10
g("google")     // segmentation fault

Will return the length if g XOR o XOR o XOR g XOR l XOR e isn't 9, else it will infinite recurse causing a stack overflow.
How it works
I used a (very) crappy hashing algorithm (a XOR b XOR c ...) to get a single number from the first six chars of the string. Collision likelyhood is very high, but if we assume the string has to be the name of an actual search engine, then the collision likelyhood is fairly low.
So, first we have i, which iterates through the string until s[i] is NUL (0), and while counting the length of the string, the selected char is XOR'd onto j, which is initialized to the first char in s. For "google", the result of this operation is 9.
The main thing this takes advantage of is the way pointers work in C. A pointer is actually a large number that denotes an address in memory, &var will return a pointer to var, while *var will dereference a pointer (grab the value at that address). Thus, *s is equivalent to s[0]. I think this is where most beginners get lost, confused and frustrated when it comes to C, like when you try to send a struct * to a function that takes struct * by sending &struct_ptr, which would be a memory address to a memory address, effectively making the compiler give an error such as function expects 'struct *' but got 'struct **'.

Also, this function uses no library functions. I assume using strlen and strcmp is cheating and/or not worth the #include <string.h>.

I think you need to give correct output for every string other than google.

@ThomasKwa Ah well, I tried.

Japt, 14 bytes
U¥`goog¤`?Þ:Ul

Try it here!
Explanation
U¥`goog¤`?Þ:Ul
U                     // U is the input
 ¥                    // ¥ is the Unicode shortcut for ==
  goog¤               // "google" compressed
 `      `             // backticks are used to uncompress goog¤
          Þ           // An undefined variable
            Ul        // l is a built-in that returns the length of U
                      // Implicit: output result of last expression

Can you explain?

@Adám Added an explanation :)

Zsh, 18 bytes
<<<$#1>$1
<^google

Try it online!
Explanation:

<<<$#1:

$1: the input
#: length
<<<: and print it

>$1: redirect that output to a file called the input
^google: try and find a file with any name other than google
<: and print its contents

So if the file created was called google, then no file will be found and an error message will appear. But if the file was called anything else, then its contents is the length of the input, and it will be outputted.

Stuck, 16 Bytes
s_l1u"google"=-/

Following a similar method to most people, will cause a divide by 0 error on "google" being input.

Common Lisp, 50 48 bytes
(defun g(s)(if(equal s"google")(g s)(length s)))

Ungolfed:
(defun g(s)                ; Define a function g with one argument s
    (if (equal s "google") ; If s == "google",
        (g s)              ; Then recurse!
        (length s)         ; Else, return the length of s in characters
    )
)

Defines a function g that accepts one string as input. If it is not exactly 'google', then it returns the length. Otherwise, it will call itself on the same string, creating an infinite recursive loop and eventually causing a stack overflow error.
Usage (inside an interactive CLISP shell):
>(load "google.lsp")
Finished loading.
>(g "foo")
3
>(g "Lisp is cool!")
13
>(g "google")
*** - Program stack overflow. RESET

This is pretty long compared to the others, but using recursion seemed fitting for Lisp.

This won't cause a stack overflow in some Common Lisp implementations (CCL and SBCL won't overflow).

GolfScript, 14 16 Characters
{.,\'google'=!/}

Like many others, simply compares the input to 'google' and divides the length by the inverse of the result.
Example programs:

With 'bing' (output: 4)
With 'google' (output: Error: Attempted to divide by zero.)

@Dennis I see your point. In it's original form it wasn't exactly reusable (you couldn't, say apply the code over an a list). Also I didn't realize that you had written a virtually identical answer in CJam well before I posted this (actually I was only vaguely aware of CJam as a language until now). +1 for your solution, too.

><>, 55 bytes
i:0(?v
31&l~<v0"google"~~.?%2l
$v?(2l<S?*=2l=6:+={
&<;n

Figured I'd give this a go, not my best golfing attempt or algorithm, though. Not a function per se, but I think that this should still qualify. I'll see if I can edit in a better version.
If you're allowed to print the length and then error, here's a 46 byte solution:
i:0(?v
2lnl~<v0"google";?%
$;?(2l<S?*=2l=6:+={

49 byte previous solution of this nature:
i:0(?v
l0nl~<v;!?=7
:;?(2l<S?*=2l=6:+=@@g3
elgoog

I'm happy to put up an explanation if there's any interest, and please let me know if there's anything wrong with my answer or if you have golfing suggestions.

Javascript ES6, 51 27 25 bytes
Hi, I'm new to code golf so this can probably be golfed much more, but here it goes:
_=>_=="google"?a:_.length

g=_=>_=="google"?a:_.length
g=_=>{if("google"==_)throw Error();return _.length}
and some test:
(_=>_=="google"?a:_.length)("bing")//4
(_=>_=="google"?a:_.length)("google")// Error: a is not defined

g("bing")// returns 4
g("google")// Error: a is not defined

Edit: Added ? to replace if and replace Error with an undefined object.
Edit 2: I realized my byte count was wrong, and removed the g=

O, 20 characters
{."google"={@}{.e}?}

Sample run:
bash-4.3$ java xyz.jadonfowler.o.O <( echo '{."google"={@}{.e}?} :f "yahoo" f o' )
5

bash-4.3$ java xyz.jadonfowler.o.O <( echo '{."google"={@}{.e}?} :f "google" f o' )
java.lang.ArrayIndexOutOfBoundsException: Can't pop from empty stack!
        at xyz.jadonfowler.o.Stack.pop(O.java:980)
        at xyz.jadonfowler.o.O.parse(O.java:407)
        at xyz.jadonfowler.o.CodeBlock.run(O.java:1031)
        at xyz.jadonfowler.o.O.parse(O.java:735)
        at xyz.jadonfowler.o.CodeBlock.run(O.java:1031)
        at xyz.jadonfowler.o.O.parse(O.java:99)
        at xyz.jadonfowler.o.O.runFile(O.java:37)
        at xyz.jadonfowler.o.O.main(O.java:20)
java.lang.ArrayIndexOutOfBoundsException: Can't pop from empty stack!
        at xyz.jadonfowler.o.Stack.pop(O.java:980)
        at xyz.jadonfowler.o.O.parse(O.java:425)
        at xyz.jadonfowler.o.O.runFile(O.java:37)
        at xyz.jadonfowler.o.O.main(O.java:20)

Scala, 36 34 30 29 characters
s=>(Set(s)-"google").max.size

Calling this function on "google" produces java.lang.UnsupportedOperationException: empty.max

Nice idea! However, I'm afraid it does not compile, one must declare s's type: (s:String)=>...
When I copy-paste it to scala's REPL I get <console>:1: error: ';' expected but '=>' found.

@Jacob it compiles if the type of s can be inferred from the context, e.g.: val s: String => Int = s=>(Set(s)-"google").max.size.

If you want us to use it like that, you must add val s:String=>Int= to your answer. The answer should be a valid Scala expression as-is.

@Jacob it is a valid Scala expression as-is: an anonymous function is a perfectly valid self-contained answer. Valid Scala expressions aren't only those that can be pasted into the Scala REPL without context. The question asks for a function that takes a string and returns an integer: in contexts in which such a function is expected, the answer will compile. However, feel free to take this to Meta.

Matlab, 50 51 bytes
Thanks to @rayryeng for removing 1 byte.
This uses an anonymous function, and exploits the fact that the error function with an empty input issues no error.
It's noteworthy that the error given for input 'google' is meta: it's an error using the error function.
@(s)eval('error(find(strcmp(s,''google''))),numel(s)')

Examples:
>> @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
ans =
    @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
>> ans('abcd')
ans =
     4

>> @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
ans =
    @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
>> ans('google')
Error using error
The message must be specified as either a string or a message structure.
Error in @(s)eval('error(find(strcmp(s,''google''))),numel(s)')

You could potentially save a byte if you used strcmp!

Slight change to your error statement... still an isequal there!

@rayryeng Oops... I should have pasted the new thing from scratch! Corrected, thanks

C# .NET, 65 bytes
int g(string s){return(s!="google")?s.Length:(1/int.Parse("0"));}

Test:
Console.WriteLine(g("str"));
Console.WriteLine(g("google"));

with C# 6.0 you can save a few characters by doing an expression-bodied method: int g(string s)=>s!="google"?s.Length:(1/int.Parse("0"));

also you could cause an exception by recursing, eventually you'll get a stack overflow  int g(string s)=>s!="google"?s.Length:g(s);

You can make it crash faster by just calling int.Parse(""). Although the infinite recursion strategy would be even shorter.

@kai Something like "".Length is shorter than int.Parse("").

@Bob "".Length just returns 0, it doesn't throw.

@DLeh Ah missed that. Whoops.

PHP 5.4+, 40 49 bytes
This one is quite unexpectedly long.
function g($x){echo[strlen($x),[]][$x==google];}

To run it, just pass a value:
g($argv[1]);

Test-cases:

$php google.php googlea
7
$php google.php google
Notice:  Array to string conversion in [...][...] on line 1
Array

I'm not sure if this can ve considered an error for this challenge or not.

One could use the over-used boring method:
function g($x){echo strlen($x)/$x==google;}

Which gives me a size of only 43 bytes.

As an alternative, one could use an exit error code, using the exit construct, for also 49 bytes:
function g($x){exit($x==google?strlen($x).'':1);}

All values between 1 and 254 are valid error codes that PHP uses when exiting.

You could use function g($x){echo$x==google?a():strlen($x);} which is 46 bytes (3 bytes shorter) and throws an actual error and not just a warning. Also your second example function g($x){echo strlen($x)/$x==google;} should be: function g($x){echo strlen($x)/($x!=google);}. / has a higher precedence than == and you have to switch it to !=as well to make it work.

Perl 6, 19 bytes
{.comb/!/^google$/}

.comb returns list of characters in string (which in numeric context is a number of characters, I use this instead of .chars because it's shorter). Because there is nothing before a period, Perl 6 assumes you wanted to call a method on $_. This is divided by a negated match on regex ^google$ with implicit $_ variable. If it matches, the value becomes 0, and Perl 6 errors because of a division by zero.
Example:
> {.comb/!/^google$/}("qwerty")
6
> {.comb/!/^google$/}("google")
Attempt to divide 6 by zero using div
  in any interactive at src/Perl6/Compiler.nqp line 62

Scala, 48
def g(s:String)=if(s=="google")0/0 else s.length

To call:
 g("bing")      //> res1: Int = 4
 g("google")    //> java.lang.ArithmeticException: / by zero

you can use an anonymous function, and shave off 4 characters. also, it will be more neat, IMHO, to use ??? rather than 0/0.

bash + coreutils, 57 49 38 36 33 bytes
[ "$1" = google ];expr ${#1} / $?

Calling it with google produces expr: division by zero.
The quotes around $1 are required in order to handle the empty string correctly.
The use of ${#1} is shamelessly stolen from Tarod's answer.

Good! But I think you're mixing bash & linux commands. If you want to, check my answer where I'm using bash to count characters. Happy coding! :)

@Tarod You're right, I should have said bash + coreutils. Combining your use of Bash to count the length of the input with my use of expr allows a shorter answer than either though - see my edit. –  Ben just now   edit

Amazing! :D I'm going to upvote you! Good job, Ben! :)

BTW, I think you should set a new title for your answer. Just 'bash'.

I don't think so - expr seems to be part of coreutils.

It's true. Thanks!

Japt, 16 14 bytes
U¥`goog¤`?Δ:Ul

Throws reference error on input of "google". Try it online!

Nice! Two tips: 1) "google" can be compressed to goog¤, wrapped in backticks. 2) == can be compressed to ¥.

Totally ignored compression. I have only scratched the surface of your language @ETHproductions, and thought this may be a great starting point for it. The \u shorthands are easily missable, better put it inside the docs.

I've added a section on Unicode shortcuts in the online interpreter. @ThomasKwa You are correct. I've edited the post.

05AB1E, 10 bytes
Code:
g“Š¹“¹Q</Ä

Explanation:
g           # Take the length of the implicit input
 “Š¹“       # Compressed version of "google"
     ¹Q     # Take the first input again and check if equal to "google"
       <    # Decrement on the bool
        /   # Divide the length by the value
         Ä  # Take the abstract value of the result
            # This is then implicitly printed

Try it online!. When the input is google, nothing is printed due to a division by zero exception.

*absolute value

Java, 84 68 37 bytes
b->b.equals("google")?1/0:b.length();

This is a java.util.function.Function<String, Integer> that divides by 0 if b is the string google.

Julia, 25 bytes
x->length(x)[x!="google"]

Try it online!

Vyxal, 7 bytes
‛»Ǒ≠/÷L

Try it Online!
‛»Ǒ≠/÷L
‛»Ǒ     # "google"
   ≠    # ↑ != input
    /   # split input into ↑ even pieces. If input is "google", this will be 0, consequently causing an error
     ÷L # Get the length of the item

You might want to clarify that it's length(^) / (^ != ^^) instead of (length(^) / ^) != ^^.

Vyxal, 8 bytes
ɽ‛»¾=ßṀL

Assumptions

Program itself is the function g
Program takes exactly one input

"Google" being in the code page dictionary allows for a 3 byte representation: ‛»¾
If input is equal to "google", case insensitive, will attempt to call a triad with too few arguments, else compute length.
Try it Online!

OCaml 42 bytes
This does exactly what is asked1: it returns a function which returns the length of its (string) argument, except when the argument is "google", in which case it fails with:

Exception: Division_by_zero.

function"google"->0/0|s->String.length s;;

It doesn’t provide any way to actually call that function, though. In order to do that, you could either write:
(function"google"->0/0|s->String.length s)"some string";;

or you could, you know, give it a name.
let f=function"google"->0/0|s->String.length s;;
f"bing";;

Unpacked, this would give:
(* let f be function with one argument. *)
let f = function
    (* If the argument matches exactly "google", return 0/0 *)
    | "google" -> 0 / 0
    (* If no previous cases were a match, give your argument the name 'string'. *)
    (* and return its length. *)
    | string   -> String.length string
;;
(* Call f with "bing" as it’s argument. *)
f "bing";;

The type of 0 / 0 is int, so the function is correctly typed as string -> int.

Well, I must admit I have not checked these pesky Unicode details.

C# 4.0, 51 bytes
int g(string s){return s.Length/(s!="google"?1:0);}
Sample:
string userInput = Console.ReadLine();
Console.WriteLine(g(userInput));

Output:
// "pogi" 4
// "google" DivideByZeroException was unhandled

CoffeeScript 43 bytes
(g)->return g.length if g!="google";throw-1

Makes an anonymous function that throws -1 if the string is "google", and returns it's length otherwise. Not as obfuscated as I wanted, though.
Link to the online testing environment.
Another variation, 1 byte longer:
(g)->if g!="google"then g.length else throw-1

Nah, too late. There is already a better answer in CoffeeScript...

PowerShell, 36 35 Bytes
param($a)$a.length/($a-cne'google')

This blatantly abuses PowerShell's dynamic casting and uses xnor's trick for dividing by zero. In PowerShell, this is a terminating error and halts execution tossing a most excellently-verbose error (the error, at 242 characters, is over 6.5x the size of the function itself)
Attempted to divide by zero.
At line:1 char:11
+ param($a);$a.length/($a-cne'google')
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

Saved a byte thanks to ConnorLSW

you can use param($a)$a.length/($a-cne'google') to skip using the the !, saving one byte.

@ConnorLSW Indeed. Thanks.

PHP 5.4, 81 bytes
<?function g($s){eval('if(isset('.($s==google?"$s":'$s').'))print strlen($s);');}
// following added for easy testing, not included in bytes count
g($argv[1]);

Everyone's favourite error when searching for Google! Didn't work out quite as obfuscated as I'd hoped...
Usage:
php 58891.php 'test'
4
php 58891.php 'google'
# error

Just thought I'd point this out: the challenge ID is 58891, not 85591. Otherwise, good job!

@ConfusedMr_C hah, good spot! I'd like to say I did that deliberately, but that would definitely be a lie!

Lua, 42 Bytes
This challenge has made me realize how hard it is to cause an error in Lua.
x=io.read()print(x~="google"and #x or t())

Takes an input and if that input isn't google than print the length of the input, if not call a function t which doesn't exist, throwing an error.

Can shave off one byte by removing the space before the '#x'.

Can shave off two more bytes on top of that by saying 'or~x' instead of 'or t()'. Throws a conversion error.

PARI/GP, 21 19 bytes
x->#x/(x!="google")

Example:
? g = x->#x/(x!="google")
%1 = (x)->#x/(x!="google")
? g("bing")
%2 = 4
? g("google")
  ***   at top-level: g("google")
  ***                 ^-----------
  ***   in function g: #x/(x!="google")
  ***                    ^--------------
  *** _/_: impossible inverse in dvmdii: 0.
  ***   Break loop: type 'break' to go back to GP prompt
break>

Prolog – 32 bytes
"google"*_:-x.
X*Y:-length(X,Y).

Defines a predicate (*)/2 that throws ERROR: */2: Undefined procedure: x/0 for the input "google":
?- "bing" * Length.
Length = 4.

?- "google" * Length.
ERROR: */2: Undefined procedure: x/0
   Exception: (8) x ? no debug

Ha nice! I tried a Prolog one and only got 56 chars (I'm a beginner). What does the * do?

@zackehh *, +, ... are valid names for predicates. They have to be written in infix notation and are quite handy for golfing because you can omit the parentheses and the comma for a predicate with two argument. a(A,B):-A is B. → A*B:-A is B.: 3 bytes saved for every invocation.

learn something new every day, thanks! ;)

PHP error via a warning(), 62, 52 46 bytes
I feel dirty for these, but it isn't about pretty:
function g($s){echo$s!=google?strlen($s):g();}

This will give "Warning: Missing argument 1 for g()" when you insert 'google', thought that was funny.
function g($s){echo$s!=google?strlen($s):die(err);}

function g($s){if($s!=google){return strlen($s);}die(error);}
PHP error as string, 46 bytes
function g($s){echo$s!=google?strlen($s):err;}

String dont have to be quoted (but should be!)

You can run these via the commandline using g($argv[1]);, or via an older PHP version's register_globals method as an GET g($_GET['string']) or whichever :)

If it is to play a bit 'dirty', you could use err instead, since it is a common abbreviature

You mean instead of the string 'error'? I wan't too sure about wether to count those bytes, so I just left it there, it's about the logic anyways.

It is. But hey, everybody knows what err means, and you save 2 bytes! Some used undefined variables to show errors. Why can't you use an abbreviation!?

I guess your right, changed it. Still thinking of another method. I could simply call a undefined function, would safe me even more, but I tough of that as cheating

I don't see it as cheating. But function g($s){$a=$s==google?:strlen;echo$a($s);} is 49 bytes long.

That doesnt work when I try it (unexpected :), php 5.4, even before calling it :(

It works for me: http://sandbox.onlinephpfunctions.com/code/e233f4c02b38825871a1b912991da08177a1bcc3

Af, after examining it, this wont work in my current php version, but clever method. I can;t use this technique yet, so it took me a moment ^_^. I came up with another method, which I also like, 46 bytes!

That's quite a funny alternative! I wouldn't have though of that!

rs, 31 bytes
^(google)|(.*)$/((^^\2))^^(1\1)

In rs, ^^ is the length and repetition operator. Used in the unary form, it will get the length of the following text (^^\2). Used in binary form, it will repeat the LHS RHS times ((^^\2))^^(1\1).
Take the input bing. The input is not google, so the second group will match, not the first. Once the substitutions take place, the result is ((^^bing))^^(1). ^^ gets the length to result in (4)^^(1), and the result gets repeated 1 time to result in 4.
However, if the input is google, the first group will match. That will result in ((^^))^^(1google) after substitutions. ^^ will just get the length of the empty string (0), so the result after ^^ is applied will be (0)^^(1google). Now the repetition operator can do its work...or not. See it will try to repeat 0 1google times. As 1google isn't a number, the output will be:
Traceback (most recent call last):
  File "c callback", line 6, in <module>
  File "<string>", line 5, in <module>
  File "<string>", line 167, in main
  File "<string>", line 125, in run
  File "<string>", line 72, in expand
ValueError: invalid literal for int() with base 10: '1google'

Live demo. (Put the input text in the box at the bottom left.)

C++14, 47 bytes
[](auto s){return s=="google"?throw:s.size();};

This is a generic lambda expression in C++14. It simply checks if the argument (string) is "google" and calls terminate if it is - else it returns the length of the string.
It can be called as such:
[](auto s){return s=="google"?throw:s.size();}("some_string"s);

Zereges has a very similar answer here written in C++11. Since this was C++14 it was O.K. by him for me to post this.

Befunge-93, 59 characters
<+1\_v#+1:~
vp00$<
<*_v#:\
v_v>$"google"*****-!#
< >00g.@>1

Befunge has no way to actually throw an error, so I just push an "infinite" number of 1s onto the stack. An error will happen somewhere eventually...
Explanation
Anyway, this works by reading in the input and simultaneously keeping track of its length.
<+1\_v#+1:~

This length is stored at location 0,0.
vp00$<

The remaining numbers are multiplied together.
<*_v#:\

This is then compared to the product of "google".
v_v>$"google"*****-!#

If they are the same (i.e., if their difference is zero), then the "error" is thrown. Otherwise, the value stored at 0,0 is retrieved and outputted.
< >00g.@>1

O, 17 bytes
{e\"google"=L@N?}
To use this function:
"wow" {e\"google"=L@N?} ~
Explanation:

e\               Get the length of the string and swap it on the stack
  "google"=      Compare the string
               ? If
            L@    True (it is google): Rotate top three elements on the stack, throwing an underflow error
              N   False (it is not google): do nothing
                   Length is printed out automatically

Ruby, 46 32 29 bytes
->s{b=Hash.new(0);b['google']=nil;b[s]+s.size}

New shortened approach:
->g{(g.to_a-['google'])[0].size}

Reduced 3 bytes with manatwork's suggestion
->g{([g]-['google'])[0].size}

Couple of tips to shorten it: new(0) → new 0; nil → p. Possibly more tips to shorten it: Tips for golfing in Ruby.

Found different approach. Thanks anyway :) @manatwork

Interesting. Which Ruby version? The 2.1.5 I use has no String#to_a method. But with the shorter [g]-['google'] works.

I missed it. Thank you very much :). My ruby version is 2.0.0p576.

AWK, 44 bytes
func f(x){return x=="google"?f(x):length(x)}

Example usages:
awk 'func f(x){return x=="google"?f(x):length(x)}{print f($0)}' <<< "non-google string"
awk 'func f(x){return x=="google"?f(x):length(x)}{print f($0)}' <<< "google"

Print: 17 and Segmentation fault (core dumped) respectively. The second one may cause your computer to run out of memory before it segfaults if you don't have oodles of RAM.
I find Segmentation fault errors to be a bit more broken than divide by zero since they don't even say where the problem is.
Something that looks more interesting would be:
func f(x){if(x=="google"){printf x;return f(x)}return length(x)}`

This would print googlegooglegooglegoogle.... wrapping around the screen until it finally produces the seg. fault, but it's not as 'golfy'
NB. Yeah, I'm a bit late to the party, but nobody had an AWK answer yet. :)

+1 for "Segmentation fault (core dumped)" -- my favourite error message

It's my favorite message, too... if I'm not the one that has to debug it. :p

On my 64-bit Ubuntu 16.04 with GAWK 4.1.3, the second one doesn't segfault but just eats all my memory until one of three things happens. A) the oom-killer kills it and says Killed, B) my window manager crashes or C) my computer overheats and switches off. Thus, I am adding a note to your answer that this answer may be harmful on machines which have a big stack.

My testing was done on a RHEL 6 machine with 128GB of RAM so thanks for the info @cat

Aha! That's funny. It is not that your machine has so little memory space that AWK gives up and segfaults immediately, it's that you have so much memory that AWK doesn't cause the kernel to kill it but instead tries to address so much memory that its virtual machine eventually segfaults. I only have a paltry 6 GB of RAM :P

At least it still satisfies the task, since Killed is still a nifty error :)

It's not wrong at all, I think recursing forever and possibly forcing a shutdown is a perfectly acceptable error

 TI 89 BASIC, 34 bytes
I did this in TI 89 for fun. There has got to be a more optimized method, but this is the best I could come up with for the moment.
f(x)
getNum(x/"google")&""0+dim(x)

Basically abuses the fact that a string divided by itself becomes 1.
0 is necessary to remove the string from the calculation otherwise you would return ("fun" + 3) which i don't think is compliant to the rules.

Alright, wasn't sure if I could post multiple answers to a solution @lirtosiast , thanks!

Julia, 26 24 chars
Two characters shorter now, thanks to Dennis.
The challenge says ‘[...]in as few amount of Unicode characters as possible’, so I’m going for ≠ and ℕ in my solution.
Anonymous function. Just assign it to a variable:
f->f≠"google"?endof(f):ℕ

In the case of "google" you get the error message:
julia> (f->f≠"google"?endof(f):ℕ)("google")
ERROR: UndefVarError: ℕ not defined

As ordinary function (26 chars):
x(f)=f≠"google"?endof(f):ℕ

ℕ is an unassigned variable, so it produces an error message.
If that doesn’t count or is against the rules, then just using !f (one char longer) instead would produce an error anyway. Boolean not is not defined for strings.

Fuzzy Octo Guacamole, 19 bytes  (non-competing)
"google".^={e}_!r_;

"google' pushes the string "google" to the stack.
. swaps the active stack.
^ gets input.
= is the rocketship operator, pushes 0 for equality, -1 for less than, and 1 for greater than as x <=> y with x as the top of the active stack, and y as the top of the inactive one.
{ and } denote an if statement, like bf's goto/if thing.  Skips the code inside braces if the top of the stack is truthy.
e errors.  That's it.
_ pops the stack, this time is just to remove the equality check result and show the input.
! sets the universal register to the top of the stack, or the length of the top of the stack for strings/lists.
r clears the register and pushes it back to the stack.
_ pops again, and
; prints.
So this checks for equality, then does a clumsy cast to int, and than prints the result.

the quotes... aren't maTCHED the song of unmatched quotes will extinguish the voices of mortal man from the sphere I can see it can you see ̲͚̖͔̙î̩́t̲͎̩̱͔́̋̀ it is beautiful the final snuffing of the lies of Man ALL IS LOŚ͖̩͇̗̪̏̈́T ALL IS LOST the pon̷y he comes he c̶̮omes he comes the ichor permeates all MY FACE MY FACE ᵒh god no NO NOO̼OO NΘ stop the an*̶̙̤͑̾̾̅ͫg͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨe̠̅s ͎a̧͈͖r̽̾̈́͒͑e not rè̑ͧ̌aͨl̘̝̙̃ͤ͂̾̆ ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟O̮̪̝͍ͮM̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ

-1 for unmatched quotes ಠ_ಠ

@tac they represent the beginning and end of the string literal.  That is intentional.

I know that, I just don't know why anyone would willingly create a language that uses unmatched things. (I know many golfing languages do it and it makes my eyes bleed)

@tac I can make it work with matched ones also if you want.

Well, I was mostly being facetious -- you don't have to change it, sorry.

eh.  I was being lazy earlier, and was thinking it would be easier to use unmatched ones.  You can just add 1, so fixed now.

Let us continue this discussion in chat.

Gogh, 20 bytes
÷GD$"google"={¤+}¦:$

Usage:
./gogh o '÷GD$"google"={¤+}¦:$' "google"

Explanation
             “ Implicit input                                              ”
÷            “ Duplicate the input                                         ”
GD           “ Push a range of [1, len(input)]                             ”
$            “ Rotate input to the TOS                                     ”
"google"=    “ Determine equality                                          ”
{¤+}¦:       “ Error if equals "google" (empties stack and tries addition) ”
$            “ Leave the length on the stack                               ”
             “ Implicit output                                             ”

Note: this answer is non-competing.

Gogh is epic.  Just saying.

C++14, 42 chars
For giggles, as I did not see a very good c++ solution. My TI-89 solution is superior at 34 bytes
[](auto s){return s.size()/(s!="google");}

Hoon, 32 bytes
|*
a/*
?<
=(a "google")
(lent a)

Uses a wet gate to avoid having to specify a/tape instead of a/*, assert that a doesn't equal "google" or panic, return the length of the tape.
> %.  "abc"
  |*
  a/*
  ?<
  =(a "google")
  (lent a)
3
> %.  "google"
  |*
  a/*
  ?<
  =(a "google")
  (lent a)
ford: build failed ~[/g/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/use/dojo/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/inn/hand /g/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/use/hood/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/out/dojo/drum/phat/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/dojo /d //term/1]

Um... is that supposed to link to urbit?

@DestructibleWatermelon Yup. Urbit provides the compiler/interpreter for the Hoon language.

Tellurium, 13 bytes
This language is newer than the question, so non-competing I guess.
i?google|d]L^

This program gets input using i, and checks if the input is "google". If it is, it tries dividing "google" by zero (d) well, that doesn't work (duh) so it throws an error.
If the input isn't google, it outputs the length of the selected cell's value (which is the input) using L^.

JavaScript, 25 bytes
p=>p=='google'?_:p.length

“However, if the given string is google (lowercase), it will cause an error.” – Will this?

Now it matches the challenge's requirement. Sadly the generic expectation is the solutions to be either full programs or functions. In both cases the input and output has to be handle either explicitly by the code or implicitly by the interpreter. So you can not assume your code will find data in some global variable.

You can make this valid in one of two ways: 1. Make it into a full program with input and output: g=prompt();if(g!='google')alert(g.length);else throw 0 2. Make it into a function: function(g){if(g!='google')return g.length;else throw 0}

Also, you don't have to explicitly throw an error; calling some undefined variable, such as _, will do the trick.

PHP, 48 bytes
eval((google==$s=$argv[1])."echo strlen(\$s);");

php -r '<code>' google -->
Parse error:  syntax error, unexpected 'echo' (T_ECHO) [...] in eval()'d code on line 1

54 bytes for a function:
function g($s){eval((google==$s).'echo strlen($s);');}

PHP, 56 bytes
function google($i){echo strlen($i)/(__FUNCTION__!=$i);}

Yes, it's a bit long, but I feel this is really in the spirit of the question. You really mustn't google google when google is the actual function's name.
The constant __FUNCTION__ holds the name of the function, which in this case is google. The rest of the functiondisplays the length of the input $i divided by 1 if $i is not google, or by 0 if it is. The latter throws an error.
Try it at Repl.it!

05AB1E, 8 bytes
g¹“Š¹“Ê÷

Uses the CP-1252 encoding. Try it online!
Explanation:
           # Implicit input
 g         # Take length
  ¹        # Get first input
   “Š¹“Ê   # != compressed form of "google"
        ÷  # Integer division (Zero Division Error if invalid)

There's no error in 05AB1E. It just doesn't push a result.

Jelly, 10 bytes
ßL⁼“æ8Ụ»$?

Try it online! (with "google" as input)
Try it online! (with "bing" as input)
How it works
ßL⁼“æ8Ụ»$? - Main link. Argument: s (string)

         ? - if...
  ⁼     $  -   the input is equal to...
   “æ8Ụ»   -     "google"
           -   then
ß          -     call the main link (segfault)
           -   else
 L         -     return the length of the input

Pyth - 15 bytes
?qz"google"'0lz

My favorite part of this is how I error. I use the ' function which takes a string, but pass 0, which is not a string.

Aceto, 19 bytes
rdM"google"J=$L€lp

Took me a while, but I finally got it. Aceto uses a hilbert curve for it's ip, which is really annoying.
r grabs input
d duplicates it
M pops the top value and stores it in quick memory
"google" pushes google on the stack, but with a lot of spaces in between.
- splits it on whitespace
J concatenates it
= pushes a bool on the stack: whether the top two values are equal
$ asserts that the top value is truthy, if not it raises an error.                                    Don't ask me why i don't have to negate it
L loads the quick memory
€ explodes the string, putting each char as a separate val on the stack
l takes the height of the stack
p prints that num

Try it online!

Brachylog, 12 bytes
"google"∧∈|l

Try it online!
Since Brachylog simply fails a predicate that tries to divide by 0, the error here comes from trying to unify the output with a list containing an entirely un-instantiated variable instead. If the input can be unified with google, it errors, and otherwise this predicate outputs the length of the input (add one more byte w to the end to make it a full program that prints the length).

W d, 10 9 bytes
This is a full program but is technically also a function.
*↔XÑ║╜▄]ÿ

Explanation
Decompressed:
-Fl'I`nakS/

After string decompression:
google"nakS/

google"n     # Does the input *not* equal to "google"?
        ak   # Find the length of the input
          S/ # Divide the length of the input by the above condition

Clojure, 47 44 bytes
Old answer
#(/(count %)(get{false 1 true 0}(= %"google")))

Try it online!
New Answer
#(/(count %)({false 1 true 0}(= %"google")))

Removed the get function call, because you can call a hashmap with a key to get the value.
Try it online!

Welcome to the site, and nice first answer! Be sure to check out our Tips for golfing in Clojure page for ways you can golf your program

@cairdcoinheringaahing thank you^^

Red, 34 bytes
func[g][length? any[g ="google"g]]

Try it online! (the code so dense that it crashes the program).

Python 3, 30 bytes
lambda x:len(x)//(x!="google")

Try it online! Python 3 port of xnor's Python 2 answer. The floor division operator is necessary to convert back to an integer instead of leaving it as a float.

bash, 55 51 34 bytes
Thanks @manatwork!
[ "$1" != google ]&&echo ${#1}||0

It prints command not found if $1 is google.

Shorter? [ "$1" != google ]&&echo ${#1}||0

@manatwork Shorter & beautiful!

C - 72 characters
g(char*s){char*p=s;for(;*p=="google"[p-s];p++);for(;*p;p++);return p-s;}

output:
g("test")    # 4
g("googles") # 7
g("google")  # Segmentation fault (core dumped)

This solution is pretty straightforward, no tricky bit manipulation (but also no library functions): match the string google in the first loop, and if there are still characters left continue to the end of the string. Return the difference between the pointers as the length.
The bug: given the string "google" the first loop does not terminate, causing it to overrun and dereference memory locations until it segfaults.
It also has a bonus bug: if you feed it the string "google\0" it succeeds but returns the wrong length.

JS, 48 bytes
An improvement over Beta Decay's JS:
function f(g){g=="google"?g.s.s:alert(g.length)}

The original for reference:
function f(g){if(g=="google")throw 1;alert(g.length)}

There's already a shorter answer.

CoffeeScript, 32 bytes
g=(s)->(s if s!='google').length

To call:
g('bing') # returns 4
g('google') # TypeError: Cannot read property 'length' of undefined

The expression (s if s!='google') evaluates to undefined if the value of the argument s is google, otherwise it gives the argument itself. In the former case, JavaScript throws an error when attempting to access a property of undefined.

Burlesque, 25 bytes
J"google"!={L[}j{vvg_}jie

Code can be run at Anarchy Golf checker. Click 'use form' choose 'burlesque', copy/paste code into the form, and input goes under it. Run.

You can shorten {L[} to qL[. q is a syntax prefix as a shortcut for Blocks that only contain one value.

XPath 2.0 (if you treat an XPath expression as a function with the context item as its argument):
Simple solution:
if (.='google') then error() else string-length()

If you treat returning an empty sequence as an error, then
string-length(.[.!='google'])

Go: 92, 63, 59 bytes with panic instead of error
func g(s string)int{if s=="google"{panic(0)};return len(s)}

Welcome to PPCG! This is a codegolf challenge, so you should remove all spaces and newlines to get a much lower byte count. You won't get many upvotes, if you post such an ungolfed version.

thanks for the welcome. But, Go doesn't allow one to stray too far away from the standard formatting, I'll update the answer in a minute

using panic() instead of returning error saves some bytes: func g(s string)int{if s=="google"{panic("")};return len(s)} (60 bytes)

PowerShell, 42 bytes
function g($x){$x.Length/($x-ne'google')}

Powershell, 60
$f={param([string]$s);if($s-eq'google'){throw $s};$s.Length}

Usage:
PS> & $f google

Throws an exception.
PS> & $f bing

Returns 4
Shortest I could come up with :(

Perl, 49 46 39 31 bytes
sub g{sub g{$_=pop;y///c/!/^google$/}}

Call with g(string), print with print g(string).
How it works
The ternary operator only evaluates the expression if the condition is met. So when the input isn't google, it simply returns the original string and passes it on to length. However, is the input is google, it tries to divide by zero and causes this error:
Illegal division by zero at filename.pl line 1.

And as we all know, dividing by zero will break the internet (and the rest of reality).
Changes

Saved 3 bytes by changing return to print and removing unneeded parentheses.
Saved 6 bytes thanks to @manatwork, and saved an additional 1 byte by re-arranging my code.
Saved 8 bytes and fixed an error thanks to @Grimy.

Wouldn't save more by returning, but implicitly, without using the return keyword? sub g{length($_[0]=~"google"?1/0:$_[0])}

@manatwork I'll add that in. Thanks!

This will incorrectly raise an error for any string that contains “google” (e.g. “ungoogleable”). A shorter and more correct version would be: sub g{$_=pop;y///c/!/^google$/}

@Grimy Thanks for pointing that out, I've added that in.

ECMA6,30
g=(s)=>s=="google"?-1:s.length

Since a string length of -1 is an error I think this is a valid answer in Javascript (ECMA6).
I was initially inspired by the python trick of causing a division by zero mentioned near the top. However this does not work in Javascript because you can divide by zero and get "Infinity" without throwing an error so I looked into other options.
This works in Chrome you can copy this into the dev console and then run it by calling g("some string here"). I assume any other browser that has partial support for ECMA6 should be able to run it.

CoffeeScript, 36 bytes
f=(x)->throw 0if'google'==x;x.length

jq, 39 characters
def g(s):s|length/({"google":0}[s]//1);

Sample run:
bash-4.3$ bin/jq -n 'def g(s):s|length/({"google":0}[s]//1); g("google")'
jq: error (at <unknown>): number (6) and number (0) cannot be divided because the divisor is zero

bash-4.3$ bin/jq -n 'def g(s):s|length/({"google":0}[s]//1); g("yahoo")'
5

On-line test:

"google"
"yahoo"

Emacs Lisp, 43 bytes
(lambda(s)(if(equal s"google")*(length s)))

Throws the error (void-variable *) for any string that equals google.

@FryAmTheEggman I'm sorry, I just wrote the explanation wrong, the code is correct.

STATA, 44 bytes
pr de a
if"google"==`0' f
di length(`0')
end

prints "unrecognized command:  f" when input is "google"

Perl5, 48 bytes
sub google{map{eval,-7+length}qq~&{"::$_[0]"}~}

google("google") and google will google("google").
Try it:
perl -e 'sub google{map{eval,-7+length}qq~&{"::$_[0]"}~} print google @ARGV' google

47 bytes
The following is one char shorter, but more fiddly on the command line:
sub google{map{eval,-6+length}qq~&{"'$_[0]"}~}

F#, 33 Characters
function"google"->0/0|s->s.Length

When "google" is provided as input, it produces a DevideByZeroException.
Usage:
let g = function"google"->0/0|s->s.Length

g "bing"   // 4
g "google" // DivideByZeroException

><>, 108 bytes
i:"g"=1-?v\]
i:"o"=1-?v\
i:"o"=1-?v\
i:"g"=1-?v\
i:"l"=1-?v\
i:"e"=1-?v\
i:01-=1-?v\
>i:0)?v~l n;
^     <  <

Try it here

AHK, 75 bytes
Inputbox,s
MsgBox % a(s)
a(b)
{
if (b!="google")
return StrLen(b)
throw b
}

there is no proper stdin and stdout support in ahk so im using inputbox and msgbox, the concept is the same tho.

Java 1.8, 33 bytes
(s)->s.length()/(s=="google"?0:1)

Explanation
The lambda takes a String named s, finds the length, and if it isn't "google", divides it by one, otherwise dividing it by zero and causing an Exception.
Usage
Note that java.util.function.Function has to be imported.

Function<String, Integer> f = (s)->s.length()/(s=="google"?0:1); //Assign function to variable
    //Note that java type inferencing automatically handles the String type

System.out.println(f.apply("elgoog")); //Prints 6
System.out.println(f.apply("google")); //ArithmeticException: Divide by zero

As far as I know, required imports need to be counted in the score, so your full code would be the import and the function.

@AlexA. The thing with Java is that lambdas are weird- the question only asked for a function, and the lambda is a function. However, Java needs to squeeze the function into a functional interface with the same method signature (accepts string, returns int), and the Java.util.function.Function interface fits the bill. However, the full function is provided. (Also see http://codegolf.stackexchange.com/a/58981/41505)

You are going to have to change == to .equals unless I'm missing something with java 8

It worked for me using the provided implementation. It may be a subtle difference between String objects and literals, but it works for me

Lua, 47 bytes
print(assert(arg[1]~="google")and arg[1]:len())

Throws "assertion failed" if it's "google"

golflua, 25 characters
\g(s)?s=="google"e""$~#s$

Sample run:
bash-4.3$ golflua -e '\g(s)?s=="google"e""$~#s$ w(g("google"))'
golflua: (command line):1:
stack traceback:
        [C]: in function 'e'
        (command line):1: in function 'g'
        (command line):1: in main chunk
        [C]: in ?

bash-4.3$ golflua -e '\g(s)?s=="google"e""$~#s$ w(g("yahoo"))'
5

Clojure - 41 40 bytes
(defn g[s](if(= s"google")(g)(count s)))

Attempts to call itself with zero arguments for the input "google".
> (g "bing")
4
> (g "google")
clojure.lang.ArityException: Wrong number of args (0) passed to: sandbox10419$g

PHP, 41 bytes
Because the division by zero is overused in the already existing answers, I tried to come up with something else (sacrificing 3 bytes):
<?=strlen($x=$argv[1])+log($x!="google");

It's not a function (the task explicitly asks to write a function) but it can be invoked from the command line in a functional manner:
$ echo '<?=strlen($x=$argv[1])+log($x!="google");' | php -- bing
4

$ echo '<?=strlen($x=$argv[1])+log($x!="google");' | php -- google
-INF

It doesn't produce an error when the argument is google but it doesn't display the length of the string google either. However it displays -INF (i.e. minus infinity) and this value can be considered an error for a function that returns a length (which, by definition, is a count, i.e. a non-negative number).
A 38 bytes PHP solution using division by zero:
<?=strlen($x=$argv[1])/($x!="google");

It can be invoked in the same way as above. When the argument is google it displays a PHP warning.

You get a +1 from me for the division-by-zero, clever! But a -1 for not making it a function as the topic states :)

-2 bytes: The quotation marks are unnecessary.

Swift, 71 Bytes
Short but lame:
print({assert($0 != "google");return $0.characters.count}(readLine()!))

Longer (75) but not lame:
print({{0/$0}($0.hash&-0x20f4f91ecf8d43)^$0.characters.count}(readLine()!))

The second one doesn't use any String literal. Works by subtracting the hash value of the input string by the "google" hashValue. Then it divides 0 by this value, resulting in a runtime error when it's 0 (0/0 = undef.) but in all other cases the result is 0 (0/x = 0). This result gets XOR'd by the character count in the String.

Hassium, 52 Bytes
func g(s){if(s=="google")throw("");return s.length;}

Run and see expanded here

func g(s)return(s == "google")?throw():s.length; is a bit shorter.

@Dennis Actually, it is 32 bits shorter.

Haskell, 24 characters
g n|n/="google"=length n

"Unexhaustive patterns" if you pass it "google".

C++, 81
int l(char *s){int b=0,i=0;do{b=s[i]^"google"[i]?1:b;}while(s[i++]);return--i/b;}

Divides by 0 on "google". This is my first C++ golf, so any tips would be welcome.
^ is used like !=. b is equal to 1 when the string is not "google", 0 if it is. So i/s will result in i/0.

TSQL 2012, 87
CREATE FUNCTION g(@p CHAR(9))RETURNS INT AS BEGIN RETURN IIF(@p='google',@p,LEN(@p))END

How to use :
SELECT dbo.g('gogle')
-- return 5
SELECT dbo.g('google')
--return Conversion failed when converting the varchar value 'google   ' to data type int.

J, 18
   #`^@.('google'-:])

Usage:
   #`^@.('google'-:]) 'googl'
5
   #`^@.('google'-:]) 'google'
|domain error
|       #`^@.('google'-:])'google'

Explanation
Count (#) if y does not match (-:]) the string 'google', but if it does match, compute e to the power of the string 'google', which is an error.

><>, 47 bytes
i:0(?\
?\ln;>~l6=
"\ "elgoog
!\{=?!\l ?
=< ;n6<

Here's a line-by-line breakdown:
i:0(?\

A standard ><> input loop, pushes the input string followed by -1.
?\ln;>~l6=

Starts at >. Discards the -1, checks the length is equal to 6. If it is, move to next line, otherwise gets the length, prints, and exits.
"\ "elgoog

Starts at \. Pushes 'google' in reverse. If the input string was google, stack is now googleelgoog
!\{=?!\l ?

Starts at the first \. Rolls the stack one to the left. If top two elements aren't equal, moves to next line. Otherwise, if the stack is length is zero, the strings are equal, so also step to next line.
=< ;n6<

Starts on the 1st < if the string was 'google'. This is only reached when the stack is empty, so attempting to pop any number of values will cause an error - in this case, = is used. If the string wasn't 'google', outputs 6 and exits.

Python, 47 bytes
a=input()
print(0/0 if a=="google" else len(a))

It should print the length of the string if the string is not "google", not the string itself. replacing else a with else len(a) will do the trick.

Zsh and bc, 29 bytes
[ "$1" = google ];bc<<<$#1/$?

Sample output:
$ zsh not_google.sh oogle
5
$ zsh not_google.sh google
Runtime error (func=(main), adr=5): Divide by zero

Explanation:
The first command exits true (zero) when the argument equals "google" and false (one) otherwise.  That exit code is stored in $? until another command completes, allowing us to divide by that number.
We then run bc (with input via herestring) to compute the length of the argument divided by that exit code.  This is either length ÷ 1 (the length) or length ÷ 0 (an error).
An un-golfed version:
if [ "$1" = google ]; then
  divisor=0
else
  divisor=1
fi
length="${#1}"
echo "$length / $divisor" |bc

Bash and bc, 31 bytes
This uses the same logic, but bash can't handle $#1 without braces:
[ "$1" = google ];bc<<<${#1}/$?

Zsh and bc, 26 bytes (also errors on empty string)
This version also has an error when given an empty string, so I assume it doesn't count.  It has the exact same output as the previous version (except when given an empty string or no argument).
bc<<<$#1/(0!=${#1#google})

Un-golfed version of 26 byte answer:
length="${#1}"                 # the length of the first argument
unprefix_google="${1#google}"  # google → "", googler → r, goog → goog, "" → ""
length_unprefix_google="${#unprefix_google}"

if [ 0 != "$length_unprefix_google" ]; then
  divisor=1                # $unprefix_google is an empty string
else
  divisor=0                # $unprefix_google is not empty
fi

echo "$length / $divisor" |bc

Go, 110 102 93 92 bytes
It makes sense to use a language developed by Google employees to Google Google!
note that this is actually a valid, compilable program, unlike the other go answer.
will take input forever until "google" is input:
package main
import."fmt"
func main(){a:=""
Scan(&a)
if a=="google"{panic(0)}
Print(len(a))}
example i/o:
bing
4
oogle
5
google
panic: 0

goroutine 1 [running]:
runtime.panic(0x480e60, 0xc21000a190)
        /usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6
main.main()
        /home/cat/projects/go/src/not-google/main.go:10 +0x115
exit status 2

ungolfed:
package main

import . "fmt"

func main() {
    a := ""
    Scan(&a)
    if a == "google" {
        panic(0)
    }
    Print(len(a))
}
apparently i had forgotten that var a string is just "" aka empty string. sigh.

Milky Way 1.0.0, 18 bytes
This language was created after the challenge was posted.
'?{"google"b~z~y!}

Explanation
'                   # read input from command line
 ?{         ~ ~  }  # if-else statement
   "google"         # push "google" to the stack
           b        # == on top two stack items (input and "google")
             z      # non-existent opcode raises an exception
               y    # push the length of the TOS to the stack
                !   # output the TOS

Milky Way (current version), 18 bytes
'?{"google"b_z_y!}

Usage
The code is called via the command line as follows:
./mw <path-to-code> -i <input>

MS T-SQL, 63 bytes
CREATE PROC g @p CHAR(9) AS SELECT IIF(@p='google',1/0,LEN(@p))

Ungolfed code;
CREATE PROC g
    @p CHAR(9)
AS
    SELECT IIF(@p='google',1/0,LEN(@p))

Called by either EXEC g 'string' or simply g 'string'
Command: EXEC g 'gogle'
Result: 5
Command: EXEC g 'google'
Result: Msg 8134, Level 16, State 1, Procedure g, Line 1 Divide by zero error encountered.

Java, 96 Bytes
This should work, but IDK for sure since I cant assess a computer at the moment:
Golfed:
 int g(String s){if(s.equals("google"))throw new
 IllegalArgumentException();return s.length();}

Ungolfed:
int g(String s){
    if(s.equals("google")) throw new IllegalArgumentException();
    return s.length(); }

I realize I could proably shorten this, let me know in the comments.

Actually, I could just divide the string google by a number and get some type-mistmatch error

Wouldn't a type mismatch be checked at compile time, not run time, because of type erasure?

@tac probably. Could be a workaround through try catch

Lua, 42 bytes
function g(s)return #(s~='google'and s)end

This creates a function g that takes an argument s and (assuming it is a string) returns the length (#) of the result of the evaluation s~='google'and s, which equates to s if s is not 'google', or false if it is. Since there is no length of false, if s is google, this will error, else, it will return the length. Simple and effective.
I know there are other Lua answers, and that I could shorten this by using io.read(), but I'm going to disregard both of those for the same reason: they don't actually use functions, like the question specifically calls for.
If I'm wrong in that it doesn't need to be a function, we can cut this to 32 bytes by doing:
s=io.read()g=#(s~='google'and s)

Mathcad, 23 "bytes"

And it even works with foreign languages ...

Note: Mathcad displays errors by showing the expression in red; clicking on the expression shows the error message.

TI-83 Basic, 21 bytes
Simple solution. (Lowercase tokens are two bytes each).
length(Ans)/(Ans≠"google

Alternate solution (22 bytes):
If Ans="google
.
length(Ans

Alternate solution (23 bytes):
length(Ans)+0/(Ans≠"google

This is exactly what I posted in a comment siz months ago. Additionally, you aren't allowed to take input through Ans anymore; there's a meta post about it.

Rust, 41 chars
rust solution, provided by a friend who does have a rep of 10 to post (and asked me to post it on his behalf).
|x:str|{if x=="google"{panic!();}x.len()}

Molecule (v5.6+), 16 bytes
I_"google"=?p¿#

Explanation:
I_"google"=?p¿#
I_              duplicate
  "google"=     add google and compare
           ?p¿  if true, do a primality test on "google"
              # get length

This way the program will error and shutdown if it does a primality test on a string.

Pyth, 12 bytes
/lznz"google

len(input())/input()!="google"

This isn't really working for me here. If I enter "Hello" It should return 5, but it returns {} 2.584962500721156, and if I enter "google" it doesn't cause an error.

@DrGreenEggsandHamDJ Try it here

The spec asks for a function. This is a full program.

Python 2, 46 bytes
a=raw_input()
print len(a)if a!='google'else b

Errors out on input of "google" because b is an undefined identifier, but succeeds on other strings since control never reaches b in those cases.

Ruby, 26 bytes
Not shorter than the existing ones, but an alternative solution.
->x{(x=='google'||x).size}

If given google, it tries to do true.size which results in an error:
NoMethodError: undefined method `size' for true:TrueClass

Clojure, 35 33 bytes
#(/(count %)(if(= %"google")0 1))

(def g #(/(count %)(if(= %"google")0 1)))

(g "google")

ArithmeticException Divide by zero  clojure.lang.Numbers.divide

(g "bing")

4

Unfortunately, 0 is true is Clojure, and there aren't any simple ways of casting a bool to an int anyways, so I had to spend some bytes on a ternary. Still ended up being shorter than my first attempt.
V1: #(if(= % "google")(/ 1 0)(count %)))

tcl, 46
proc x s {if \$s=="google" !;string length $s}

demo

SmileBASIC, 41 38 bytes
DEF G(S)RETURN LEN(S)/(S!="google")END

If S is not google, the length is divided by 1. Otherwise it's divided by 0, causing an error.
G("SAND")
4

G("google")
Divide by 0 in 0:1

Edited processing JS: 68 bytes
var a =function(i){if(i==="google"){throw"a";}else{print(i.length);}};

Used a edited version of processing. When run here you can see it works. If you input google then the error buddy pops up without any message. This is my first golf!
Edited version of processing (didn't cheat by making my own version) https://github.com/Khan/processing-js

Who edited it? Because you aren't allowed to edit a language to improve your score.

I did not edit it. The khanacademy team edited it. https://github.com/Khan/processing-js It is its own fork.

That's ok then. Just checking ;)

Yeah otherwise my language would be called g. It would just have functions called with one byte :P

Smart idea! Why don't you make it?

It is against the rules.

Just say that it's non competing. Check mine above you.

Let us continue this discussion in chat.

Ruby, 19+1 = 20 bytes
Uses the -n flag. Because -n includes the trailing newline for any line of input, it must be piped in from a file w/o the trailing newline or it will not give the error and will instead return 7.
p +~/(?<!^google)$/

Version that requires a trailing newline in the input, so you can type in directly from STDIN, for 20+1=21 bytes
p +~/(?<!^google)\n/

Alternate version that works with or without trailing newlines, for 23+1=24 bytes.
+(! ~/^google$/&&p~/$/)

All versions return the following error:
undefined method `+@' for nil:NilClass (NoMethodError)

GNU sed, 137 bytes
Adding to the diversity of languages used here, I present a sed answer. There are no integer types or arithmetic operations in sed, so I wrote an increment method to get a string's length (111 bytes).
/^google$/{:;s:a*:&&a:;t}
s:^:0,:
:i
s:^9*,:0&:
s:.9*,:/&:;h
s:[0-9]*/::
y:0123456789:1234567890:
x;s:/.*::
G;s:\n::
s:,.:,:
/,./ti
s:,::

The first line of code checks if the input string is google, and if so it continuously increases the pattern space until a memory allocation error is raised. Try it online!
Tests: from a virtual Linux OS I setup with low memory
test@test:~$ sed -f google_error.sed <<< "yahoo"
5
test@test:~$ echo $?
0
test@test:~$ sed -f google_error.sed <<< "google"
sed: couldn't re-allocate memory
test@test:~$ echo $?
4

C, 35 bytes
-Df(s)=strlen(s)/strcmp(s,"google")

Compiler flag :) Returns the length of the string provided. If it's google it throws a Floating point exception.

How does this return the length of the string? It seems like this would return a negative result in some cases.

Mathematica, 33 bytes
#=="google"&&1/0||StringLength@#&

TFW Length doesn't work on strings. >.>

05AB1E, 10 bytes
“Š¹“Qi.0ëg

Try it online!

“Š¹“       # Push "google".
    Qi   # If input == "google"...
      .0   # Divide by 0.
     ë   # Else...
      g    # Return length of input.

....0 is divide by 0? Why?

Why the built-in in the first place when 0/ could have achived the same result with the same bytecount?

Common Lisp, 50 bytes
(lambda(n)(assert(not(equal"google"n)))(length n))

Try it online!

Stax, 9 bytes
ôK▓ÿσ▄Ω?╠

Run and debug online!
Well, defeated some of the 10-byters ...
Explanation
Uses the unpacked version to explain.
`!:X9`|^hy%
`!:X9`         "google"
      |^       array xor (can't use `-` here, which means **set** difference)
        h      head of array, error if it is empty
         y%    length of input

JavaScript (V8), 41 bytes
s=>s[['length']['google'==s|0]].toFixed()

Try it online!
JavaScript (V8), 33 bytes
s=>[_=>s.length]['google'==s|0]()

Try it online!
JavaScript (V8), 28 bytes
s=>[s]['google'==s|0].length

Try it online!

05AB1E, 8 bytes
'Š¹QiFëg

Try it online!
'Š¹QiFëg  # full program
    i     # if...
          # implicit input...
   Q      # is equal to...
'Š¹       # "google"...
     F    # then...
          # (implicit) do nothing...
          # implicit input...
     F    # times
      ë   # else...
       g  # push length of...
          # implicit input
          # implicit output

Not tying anymore lol ;p

Racket, 46 bytes
(λ(x)(if(eq? x"google")(-)(string-length x)))

Try it online!
Gives an arity mismatch error on the input "google" since - needs at least one argument.

Python 3.8 (pre-release), 37 35 bytes
lambda s:len(s)if"google"!=s else~s

Try it online!
Reverted to this solution whilst comparing to the other answers and noticing that it was the same. -2 bytes thanks to the suggestion by Makonede to use ~s instead of s.s
Raises TypeError: bad operand type for unary ~: 'str'

-2 bytes by using else~s instead of else s.s. ~ is bitwise NOT, where ~x is equivalent to -x-1. Since this doesn't work on strings, it raises TypeError: bad operand type for unary ~: 'str'. You can also golf off the space after else since there's an operator right after it

Note: you can also replace ~s with -s, +s, +a, -a, ~a,  a, etc. with any one-char undefined variable

Whispers v1, 53 bytes
> Input
> "google"
>> #1
>> 1≠2
>> 3÷4
>> Output 5

Try it online!

Red, 46 bytes
func[a][(length? a)/ either a ="google"[0][1]]

Try it online!
My first attempt on writing something somewhat serious with Red
sighs in boolean cannot be used as int

I think func[a][either"google"= a[length? a][1/0]] may work (spaces may need to be added). ~42 bytes

@Wzl no it dosen't work ( I have even tried shuffling some stuff around, it still dosen't work though )

oh sorry I mean func[a][either"google"= a[1/0][length? a]], although it sounds like you tried that

(length? a)/ make 0 a <>"google".

GNU sed, 102 bytes
I did stumble over this 137 byte sed solution, but besides the counting method can be improved the probably shortest way to produce an error with GNU sed is using the e flag to execute illegal code:
s/^google$/./e
s/.$/#/
:1
/#9*$/s/#/&0/
s/.9*$/_&/
h
y/0123456789/1234567890/
x
G
s/_.*_//
s/.//
/#/b1

Try it online!
Of course, you could save two more bytes using the buggy old version with empty labels.

TypeScript's Type System, 113 (or 73) bytes
type F<I,S=I,L extends{}[]=[]>=S extends`${infer A}${infer B}`?F<I,B,[...L,A]>:I extends"google"?F<I>:L["length"]

Try it at the TypeScript playground!
Recursively take each character of the string and put it into a list. When no characters remain, check if the initial string was "google"; if so, recurse with the same initial string (i.e. recursion error), otherwise return the length of the list. (We must split the string into a list of characters because that's the only way to get the string's length in TypeScript's Type System.)
Or, by taking input as a tuple of characters instead of a string - 73 bytes:
type F<S extends{}[]>=S extends["g","o","o","g","l","e"]?F<S>:S["length"]

Try it at the TypeScript playground!
We can skip the whole recursive splitting process by taking the input directly as a list of strings, and comparing to the split string "google", with the same recursion error idea as the above.

Rust, 170 bytes
I didn't see anything in rust, so I figured I'd make one. Hopefully someone can improve this a bit! (or perhaps a byte... see what I did there ;) )
use std::io;fn main(){let s=io::stdin();let mut b=String::new();s.read_line(&mut b).unwrap();let l=b.len();b.truncate(l-2);assert!(b!="google");println!("{}", b.len());}

Throws the error:
thread '<main>' panicked at 'assertion failed: buffer != "google"', main.rs:7

when you try "google."
Ungolfed Code:
use std::io;
fn main() {
    let stdin = io::stdin();
    let mut buffer = String::new();
    stdin.read_line(&mut buffer).unwrap();
    let leng = buffer.len();
    buffer.truncate(leng-2);
    assert!(buffer!="google");
    println!("{}", buffer.len());
}

Clojure (43 bytes)
I know Clojure has been answered before, and shorter too, but I love the way this one generates a StackOverflow error when "google" is passed in:
(defn f[s](if(= s "google")(f s)(count s)))

Example:

user=> (f "google")
StackOverflowError   user/f (NO_SOURCE_FILE:213)

Groovy, 32 chars
e={(it=='google'?0:it).length()}

A similar approach like a bunch of others here. The closure tries to return the length of either

the passed string, if it's not equal to google
the length of the integer 0, if the passed string is equal to google, which results in a MissingMethodException as there's no Integer.length() method

Tested with
e('bing')
e('google')
e('duckduckgo')

No need to assign to a variable, anonymous functions are allowed. .size() is shorter than .length() and is still not implemented for integers. {(it=='google'?0:it).size()}

Ruby, 41 characters
def g(s)puts s!="google"?s.length: a end

Powershell 34 Bytes
param($a)$a.length*($a-ne'google')

Multiply length by 0,1 boolean value of not-equal google.
Gives 0 if google (not case-sensitive), length otherwise.

Your answer should be case-sensitive, and should throw an actual error for google.

, 15 chars / 21 bytes (noncompetitive)
ï≔`google`?$:ïꝈ

Try it here (Firefox only).

why noncompetitive?

Language was made after the challenge.

Game Maker Language, 60 bytes
a=argument0;if a="google"a=1/0show_message(string_length(a))

"Your task is to create a function that accepts 1 string..." This does not meet specs, but all you would have to do is replace the first and last a with argument0.

You're right, fixed.

ಠ_ಠ, 110 bytes (noncompetitive)
ಠ_ಠ
ಠgoogleಠ
ಠ=ಠ
ಠ"ಠ
ಠ$ಠ
ಠ$ಠ
ಠ11ಠ
ಠ13ಠ
ಠ(ಠ
ಠ?ಠ
ಠ_ಠ
ಠ#ಠ
ಠ^ಠ

Try it here.

Factor, 55 53 49 bytes
: g ( s -- l ) dup length swap "google" = not / ;

Throws the string "google". throw happens to be the same length as 0 0 /. Or I could just divide a string by a number... Or I could just divide the length of the string by if it's not google...
Example use:
cat @ mint-kitty : ~/projects/factor/factor(master??!) $ ./factor -run=listener
Factor 0.98 x86.64 (1742, heads/master-0bb3228063, Tue Mar 15 14:18:40 2016)
[Clang (GCC 4.2.1 Compatible Ubuntu Clang 3.6.2 (tags/RELEASE_362/final))] on linux
IN: scratchpad : dont-google ( str -- int ) dup "google" = [ throw ] [ length ] if ;
IN: scratchpad "bing" dont-google

--- Data stack:
4
IN: scratchpad "google" dont-google
google

Type :help for debugging help.

--- Data stack:
4
IN: scratchpad

The error in the UI:

Scratch, 16 bytes

(scoring used)
Stopping the project is the closest thing to an error that I can get.

I think this should be 6 bytes + "google" = 12 bytes...

Google=6 bytes, 6 blocks, 2 operators, 2 variables.  6+6+2+2=8+8=16

Shouldn't you use a divide by 0 error (only one I know of)?

Does not error in Scratch v456.

C++, 77 Bytes
#include <string>
int G(std::string S){1/int(S!="google");return S.length();}

Excel VBA, 52 Bytes
Subroutine that take input a as unassigned/variant of expected type variant/String and outputs to the VBE Immediates window. If a = "google" throws Run-time error '3': Return without GoSub else outputs the length of the input a.
Sub g(a)
If a="google"Then Return
Debug.?Len(a)
End Sub

shortC, 21 bytes
Df(s)Ss)/Ms,"google")

Df(s) defines a function f that takes one argument s.
Ss) calculates the length of s.
Ms,"google) compares s to "google".
Ss)/Ms,"google") divides the length of s by 0 if the strings are equal. This throws floating point exception if they're equal.

Try it online!

Syms, 18 bytes
{[#~{google}=!1/]}

Try it online!

Bash
[ $1 == google ]; return $((${#1}/$?))

GameMaker Language, 46 bytes
x=argument0
return string_length(x)/x!=google

Uses the same logic as this Python answer, abusing GMLs type coercion making the function divide by zero if the string equals google
I also haven't and can't test this because I currently don't have GameMaker installed, just made this from memory

Keg, 16 bytes
:`google`=[0/|÷!

Try it online!
Attempt ruined by the fact that google isn't in Keg's dictionary. That's why I use DuckDuckGo, which at least has parts of it's name in the dictionary!

Lua, 35 bytes
load'return #(...=="google"or ...)'

Try it online!
Idea is like one in @QuertyKeyboard's answer, but better optimized: load is used to create function and inverting check for "googleness" allows us to save one byte by replacing and with or.
Again, if full programs are allowed, we can cut down to 29 bytes!
Lua, 29 bytes
print(#(...=="google"or ...))

Try it online!

VBScript, 47 bytes
sub f(x)
msgbox len(x)/abs(x<>"google")
end sub

VBScript will return -1 for True, so we have to abs() it. And attempts to divide it by the length, like the python answer.

Why abs than -?

Knight, 17 bytes
O/L=gP!?g"google"

Try it online!
Requires a patch to fix an errata in the """golfed""" C interpreter, where it will leave a newline in the input from PROMPT. This matches the behavior of the AST interpreter and the wording of the spec.
This is the simple division by zero method.
# print length(g = prompt()) / (g != "google")
OUTPUT / (LENGTH(= g PROMPT)) (! (? g "google"))

Relies on division by zero throwing an exception. The AST interpreter will always throw an exception in software, but for the golfed interpreter, it requires the x86 behavior of throwing an exception on the hardware level.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes