Java exceptions guide

This is intended as a dumping ground for all the tips on using exceptions that I accumulate over the years.

Don't swallow exceptions

Never, ever do this:

try {
  ...
} catch (IOException ioe) {
  // do nothing here
}

Always log a message, or print a stacktrace, or re-throw the exception, or throw a new exception (and wrap the caught exception).

Allow your checked exceptions to wrap other exceptions

class MyException extends Exception {
  public MyException(String message, Throwable cause) {
    super(message, cause);
  }
}

This is almost always useful. You will often find yourself catching an IOException and re-throwing it as your own exception. The main point is DON'T DISCARD THE ORIGINAL EXCEPTION. If you do, you won't see it any stack traces as the "caused by:" exception.

Don't log an exception that you are re-throwing or wrapping

This is a minor detail but it makes for much cleaner logs.

try {
  ...
} catch (IOException ioe) {
  log.error("Got an IOException", ioe); // not necessary
  throw new MyException("Had a problem contacting the server on port " + port, ioe);
}

In the above, assuming the logger is log4j or something similar, it is going to print the stacktrace for the IOException exception. Then whatever catches MyException up the stack will also log the IOException. This makes for message logging. Either log the IOException and do not wrap the IOException, or don't log it and just wrap it.

Create your own top-level exception classes

I've often found it useful to create two top-level exception classes, one that extends Exception and one that extends RuntimeException. For example, ABCCompanyException and ABCCompanyRuntimeException. Sometimes at the top-level of your application (in the main() method or the HTTP request handler, for example) you want to catch everything that hasn't been dealt with yet. It can be useful to handle "ABCCompanyException" and it's sub-classes separately from Java's "Exception" or "ABCCompanyRuntimeException" separately from Java's RuntimeException.

Don't forget to catch run-time exceptions in callback methods

Let's say you're implementing an event handler to be used in a third-party event bus framework, or implementing an "onOpen/onClose/onMessage" type interface for a web socket client. You should wrap the entire body of the method in a try...catch (Throwable t) otherwise a run-time message might be thrown somewhere, bubble up into the third-party library, and be swallowed there. Do this any time you are implementing a method that you don't actually call yourself. The same thing goes for the run() method in the Runnable class.

eyefiserver2 - A standalone Eye-Fi Server in python, for linux

I recently forked the defunct eyefiserver project. The new project is called eyefiserver2. It is a server for eye-fi cards that runs on Linux using Python, however, it should be possible to run it on any OS, I just haven't tested it on anything other than Linux.

Topic: 

Social Networking Bullshit

I'm tired of all this social networking bullshit. I mean the social networking bullshit that is always asking me to click something, creating visual noise, and generally just pissing me off because I'm not interested in sharing everything I do with the world. Today I purchased some books at Chapters and after my purchase went through I got this screen asking me if I want to "tell my friends about my purchase" on Facebook, LinkedIn, or Twitter.

[img_assist|nid=403|title=Chapters - Share Your Purchase|desc=|link=none|align=left|width=501|height=233]

The only good thing to come of this is that as more and more people share useless information on social networks that no one cares about (like your lastest high score in some game that no ones care about but you, or your recent check-in at a local business, or something that you liked), more are more people will get pissed off and stop using them. I barely go to Facebook anymore because I find the ratio of crap to quality is monotonically increasing. Google+ is a bit refreshing because they are so few people that use it, there is therefore less crap; however, I can still use it for the things that matter to me, like sharing photos and videos with close friends and family (not the public), even those that aren't actually signed into Google+.

It's probably because I'm getting old, and being older and wiser, I can see things for what they are. I have no illusions that my friends will care what I buy at Chapters, and I know that Chapters just wants to sell more books. It's a little thing, but when combined with other things (the new Plum points crap), it's another reason to shop somewhere else instead.

I Just Tried Windows 8

I just tried Windows 8, and to be honest it's pretty awful. It looks like it's meant for running on a touch screen but if you are a desktop user it's horribly awkward to use. I'm not sure if it's a bug but getting the task bar thingy (what's it called?) to show up on the left-hand side of the screen is very difficult. I seem to have to hover on the top-left corner and wait for an icon to appear, then move downward, then the whole task bar thingy will appear. Now that I am in the Maps App, I have to go to the bottom-left corner and a "Start" thingy appears but I have to move very fast to it before it disappears (and for some reason, clicking on it right now doesn't do anything, so I seem to be stuck in the Maps app). Ok, I seem to be able to get the Start menu button to appear at the bottom-left but clicking on it doesn't always work.

There does seem to be an app called "Desktop" but it doesn't seem possible to launch any apps from it. It just has a Windows Explorer and an Internet Explorer icon. The menu in Windows Explorer also seems horribly complicated (I guess this is the whole "ribbon" thing). Shudder. It's just awful.

All the apps seem to be full-screen, at least all the apps accessible from the "Start screen" (is that called "Metro"?). Not really sure what the deal is with that. How are we supposed to work with two applications at the same time? I can't seem to launch apps from the "Desktop" I have to launch them from the "Start screen".

I didn't think it was possibly to make something worse than Ubuntu's Unity, but it seems that Microsoft has managed to do that. BTW, I am starting to like Unity more and more (although at the moment I am taking a short break and using KDE4 instead).

Moving Data from One Database to Another with Django

So I have a django database I'm working on and I decided I wanted to do the development in sqlite3 instead of mysql. I decided to do this because it makes it easier, for example, to have someone else work on HTML/CSS if I can just give them a directory, tell them to run a bash script and go to http://localhost:8000, rather than them having to do all that AND setup a mysql server. Sure, that can also be done with a script, but with sqlite things are just a hell of a lot easier in some ways.

I decided I wanted to take the data out of my mysql database and load it into a sqlite db. Not so simple, you can't just take an SQL dump from mysql and import it into sqlite3. I started Googling around for "mysql to sqlite" and didn't really get anywhere. I then realized that Django can already talk to sqlite and mysql transparently without me having to know any SQL. So I thought about writing my own python modules to do this, but it turns out someone has already done it.

The django-extensions project has a manage.py command called "dumpscript" that "Generates a Python script that will repopulate the database using objects. The advantage of this approach is that it is easy to understand, and more flexible than directly populating the database, or using XML." This was exactly what I wanted.

Tags: 

B.C. First-Time New Home Buyers’ Bonus is a Stupid Idea

A few days ago the B.C. government announced a new $10,000 bonus for new home buyers. Not only is this a stupid waste of money that could have been diverted to many more important things, it may not actually do anything to improve affordability as housing prices will surely go up accordingly. Even Cameron Muir, who is generally wrong about everything, is probably correct when he says "That should induce additional sales activity, as well as later on we’ll likely see housing starts rebound as a result of that demand . . ." It's reminds me of when the federal government allowed people to carry 30, then 35, then 40 year mortgages in order to help people afford a home. This back-fired and caused housing prices to sky-rocket even further than the already were.

Preschoolians: the internet's most ridiculous company

We ordered a bunch of shoes online for my daughter, from various American companies. One of them was Preschoolians (I'm not going to link to their site. There is an entire blog devoted to how much Preschoolians sucks but the last post was from 2006 so I decided to give them a try anyways.

First, I tried to order an "Accufit measuring device." The order was cancelled by Preschoolians and they said the following: "We would like to inform you that the for the moment we do not ship Accufit measuring devices and unfortunately your order was automatically canceled by the system . Please accept our most sincerest apologies for any inconveniences this may have caused you."

August 20th, 2011: I went ahead an ordered some shoes. I received a standard email stating that once the item ships I will receive a tracking number.

September 9th, 2011: I inquired about the order and they replied, "We would like to inform you that we have checked with the manufacturer to know exactly when your order will be shipped. They have confirmed that the shoes were made and will be shipped in 1-2 days, with the next shipment. The shoes will be delivered to you next week, and we will also send you an email with a UPS tracking number, to know exactly the estimated delivery date."

September 13th, 2011: The refunded the shoes, but stated that the shoes will be sent anyways as a gift! "First of all, please accept our apologies for the delay. We would like to inform you that the full refund was issued, and the money will go back in your account in no more than 2-3 business days. The refund was issued in order to make up for the delay. We would also like to inform you that the order was not cancelled and that the shoes will still be delivered to you as a gift."

October 18th, 2011: I inquired again, and received this reply: "Please note that we were informed that the problems we have been facing at the factory were solved so, all overdue orders should start shipping by the end of the week. We do apologize about the delay."

November 13th, 2011: Apparently the shoes are on their way via USPS: "We would like to inform you that the order for the I'm Walking Barefoot Fly Away Dark Purple Light Purple size: 25 was just shipped to you and it is transit with USPS and should be delivered to you in Canada the following days. Please accept our most sincerest apologies for any inconveniences this may have caused you."

Now it is January 3rd, 2012. If I check the status of the order online, there is a UPS tracking number (not USPS). The order is in the "waiting for UPS" state. Apparently they created a tracking number/label but never got UPS to pick it up. The number was created August 21st, 2011, the day after I ordered the shoes.

This company is an absolute joke. Most of these emails are obvious lies, as my wife said near the beginning, after the refund was issued and they said they would still send them as a gift: "Omg, they are never coming."

BTW, if you want a recommendation on where to buy toddler shoes online, check out Pediped, See Kai Run, and Robeez. Some other companies we didn't order from include Soft Star Shoes, Vivo barefoot, Teva, Land's End, and Feelmax.

Linux Mint Debian Edition: One word: FAST

I'm just trying out Linux Mint Debian Edition and the best part about it is how fast it is. The desktop is super responsive, almost feels like a new fresh Windows machine in that respect. User switching is also super fast and works perfectly, something that Ubuntu had never quite mastered. Most importantly, however, is the fact that it is not using Canonical's Unity, but instead it is still using Gnome 2.

It's been a long time since I have used an almost-pure Debian distribution but it feels good to be back. My Linux evolution went something like this: Redhat->Corel (debian)->Mandrake->Debian->Gentoo->Ubuntu->???. I will definitely move to something Debian-based or possible Gentoo. I may keep the LMDE on my laptop and put back Gentoo on my desktop. Unity is just plain awful and should never have seen the light of day. Ubuntu was great when it first started and it was basically a Debian derivative that just worked. Nowadays Ubuntu is a different beast. It's slow, awkward, cumbersome, bloated, and I can't stand the fact that they are forcing Unity down people's throats. I'm positive that Unity will be a failure in the end.

Myths about the Vancouver housing bubble

I just had a listen to this CBC interview with some writer about the housing situation in Vancouver: Young Adults Leaving Vancouver.

He was asked about whether the housing bubble is due to speculation. Of course there is speculation. It's rampant. Even the average Joe that is buying a home and maxing out how much the bank will lend him is speculating. Someone who is selling their current place (that they bought in the 1990s) and buying a larger house now is speculating. They are all speculating that the market value of housing will increase even further (or stay where it is and not go down). It is this speculation that is lifting prices. There are not enough people sitting on the fence waiting for the market to crash, in order for a crash to happen. This is the way bubbles work (see: every bubble that has ever occurred). Speculation is the nature of bubbles. Some of the speculation is explicit, the rest is implicit. There are lots of people who also speculate that interest will never go up. That's a costly gamble to take when maxing out your credit on a new home.

This Tyee guy has bought into everything the talking heads are saying: 1) money is coming from offshore, 2) if there is a crash it's won't be much, maybe 20%, 3) Vancouver is different, 4) It's gone on for so long, therefore the market will never go down. It's all bollocks!

1) First, locals are just as responsible here for paying exhorbitant prices. Secondly, in the 1990s there was lots of money coming from Hong Kong and elsewhere and prices did not increase very much, they stayed where they were in spite of a massive influx of money. Lastly, any "local" who takes that "offshore money" and puts it back into the housing market is also playing a part in fuelling the housing bubble. I can't tell you the number of times I've talked to a "local" who owned more than one property as an "investment". Again, it's the locals (as the majority) who are the major cause of the housing bubble in Vancouver.

2) If there is a crash, it will most likely be huge. When bubbles pop, that's the way it goes. To think otherwise is to believe there isn't a bubble.

3) Vancouver is not different! Other cities in Canada and around the world had or have real estate bubbles as well. Some have crashed already and some have yet to crash. It's not just here (where there is supposedly all this "offshore money" flowing in), not is this a recent phenomena. This kind of thing has been happening for centuries and they always say "it's different here" or "it's different this time". It's not.

4) Just because we haven't had a crash yet doesn't somehow mean that we have reached a new normal and that it will never crash.

You can find other commentary here.

Android Apps That Will Drain Your Battery

I have been having a hell of a time with my new Nexus S. The battery life has been abysmal. I have finally paid close attention to the battery use screen and began removing applications. These are the applications so far that were using a lot my battery's charge:

  • Google Latitude - Cannot be uninstalled on a stock Android phone, so just log out of it.
  • Twitter

Some applications were suprisingly good about not using up much battery:

  • Gmail
  • Skype

I'll update this list as I find more applications that use up lots of battery.

Tags: 

Yelp sucks big time

Update: Yelp has now un-filtered all my reviews.

Yelp sucks so much. I created 5 reviews on Yelp and each one of them has been filtered. The first review I created was a 1 star review for Crocodile Baby, a baby store with some of the worst customer service I have seen in many years (an opinion that is shared by several of our friends as well). The review was terse and to the point, and I suspect I've been black-listed ever since then. Their automated system that checks for spam is supposed to be aggressive and have some false positives but 5/5 of my reviews being essentially marked as spam is ridiculous.

Tags: 

My first Android application

I've just created my first Android application. I was surprised how simple it was to create but most of all how easy it was to deploy. It was available on the Android marketplace immediately with no hassle. I'll provide another post about once the application is a bit more mature. It's basically just a simple calculator application for physicians.

How-To get an unlocked Samsung Galaxy S to work with Fido

I got my wife an unlocked Samsung Galaxy S (the "Captivate" variety) and had a few challenges getting it set up.

Configuring the Fido APN

There are at least two ways to configure the Fido APN although you find even more configurations if you search online. I ended up getting the Fido APN settings from Rogers directly. The instructions were for the Nexus One, but it doesn't matter to Rogers/Fido what device you are using, all Smartphones look alike to the carrier as far as I can tell.

Here they are as they appear on my phone:

Fido Access Point Settings (Settings->Wireless and network->Mobile networks->Access Point Names)

  • Name: fido
  • APN: fido-core-appl1.apn
  • Proxy: <Not Set>
  • Port: <Not Set>
  • Username: <Not Set>
  • Password: <Not Set>
  • Server: <Not Set>
  • MMSC: http://mms.fido.ca
  • MMS Proxy: 205.151.11.13
  • MMS Port: 80
  • MCC: 302 (retrieved from SIM)
  • MNC: 370 (retrieved from SIM)
  • Authentication type: <Not Set>
  • APN type: internet + mms

The tricky part was that I had to enable "Data roaming" (under Settings->Wireless and network->Mobile networks->Data roaming) for this to work (finally found this out thanks to this thread about Fido network issues. The reason is that Fido phones are actually roaming on the Rogers network (or maybe it's what used to be Fido's network before they were acquired). It's roaming for free, but it's still technically-speaking roaming so without enabling this option the APN settings above won't work. There are other configurations online that use the fido.internet.ca APN, however, the fido-core-appl1.apn one is what you should use if you have/ a smartphone as supposedly it is faster.

You can confirm if you device is roaming by going to "Settings->About phone->Status->Roaming".

Incoming text messages timestamp bug

Incoming texts will appear to have been sent four hours ago (if you and the sender are in Pacific Standard Time). This has something to do with Android applying a timezone adjustment again, even though the message has already been adjusted by the provider before it arrives at the phone. Thanks to this thread about this timestamp bug, I was able to fix the problem by setting the Date/Time to "manual" rather than "automatic", changing my timezone to GMT-3 (Greenland) and then changing the time to be what the actual local time was. This works because GMT-3 is 4 hours ahead of PST-7 which cancels out the 4 hours that Android is subtracing from every message that comes in. The problem with this is that if you sync with Google Calendar, all the event times will be screwed up. I have since set the time back to "automatic" and I am hoping that the Froyo 2.2 update fixes this problem.

Update (2010/12/28): Thanks to this thread about SMS time differences I was able to find this app called SMS Time Fix. It works perfectly.

Updating to ECLAIR.UCJH7 (AKA JH7)

After updating the firmware to JH7 (a minor update to Android 2.1) with Kies, I could no longer connect to Kies. I tried everything imaginable, but the only thing that worked was to factory reset the device.

Constant reboots

I installed an app called Quick Profiles which caused the device to do what I would describe as a "soft reboot" (the screen goes black for a few seconds, and it returns to the locked-out screen, but all the services restart, like the wallpaper and the media scanner, so it's as if the desktop and all of its applications crashed. The only way I was able to fix this was by doing a factory reset. In the future we will back up all the settings and apps before installing a new app, then we can do a factory reset and then restore if anything goes wrong.

Update (2010/12/28): Installed MyBackup Pro and scheduled nightly backups to the SD card and online. Seems to be working like a charm so far, although I haven't actually tested the backups by doing a restore.

Pages

Subscribe to David Grant RSS