Welcome!

Java Authors: Maureen O'Gara, Bruce Armstrong, Liz McMillan, Walter H. Pinson, III, Yakov Werde

Related Topics: Java

Java: Article

Using Java's Exception System to Sing 99 Bottles of Beer

One of my friends was inspired to do a Python variant that used the same technique

Mike Galpin's Blog

First off, if you like programming, you should check out this hilarious site on the venerable song 99 Bottles of Beer.

Ok, now I am assuming that you just spent the last hour or so at that website, but you are back. If you are into Java, one of the most interesting solutions is one that eschews typical control structures (for/while/do loops) and instead uses Java's exception system to sing the song.

Actually the way that I came across the site was from an email sent by one of my colleagues. He was amused by the exception based solution. I was amused, too. Obviously such code will perform exceptionally bad (pun intended.)

One of my friends was inspired to do a Python variant that used the same technique:


#! /usr/bin/env python

class BottleException(Exception):
def __init__(self, i, c):
self.cause = c
self.cnt = i
try:
a = 1/(99-i)
raise BottleException(i+1, self)
except ZeroDivisionError:
pass

def getCause(self):
return self.cause

def printStackTrace(self):
print("%d Bottle(s) of beer on the wall,
%d Bottle(s) of beer" % (self.cnt, self.cnt))
print("Take one down and pass it around,")
print("%d Bottle(s) of beer on the wall"
% (self.cnt - 1))
try:
self.getCause().printStackTrace()
except AttributeError:
pass

try:
raise BottleException(1, None)
except Exception, e:
e.printStackTrace()



He and I are both pure hackers when it comes to Python, so there are probably numerous improvements that can be done to that code.

More Stories By Michael Galpin

Michael Galpin is an architect at eBay, specializing in presentation technologies. He has been hacking on the web since the 90s, is a frequent writer for IBM developerWorks, and has a degree in mathematics from Caltech.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.