Duncan's blog

May 20, 2013

Try, Catch… Ignore!

Filed under: Javascript — duncan @ 8:53 am
Tags: , , ,

I was using JSLint today before committing in a javascript file. It was doing some presentational effects we didn’t expect to work in all browsers, so there was a try-catch wrapped around it. And the catch block was empty.

Something a bit like this in fact:

	try {
		...			
	} catch (exception) {
		//browser does not support doing this, so catch error and continue
	}

JSLint gave me this error message:
Expected ‘ignore’ and instead saw ‘exception’.

A very useful answer on StackOverflow explains what this is about. Douglas Crockford has decided that if you have an empty catch block, your variable should be called ‘ignore’, to make it clearer you’re doing this deliberately and haven’t just forgot to do something with the exception.

So this code works:

	try {
		...			
	} catch (ignore) {
		//browser does not support doing this, so catch error and continue
	}

And conversely it only works if you don’t do anything in that block. i.e. this code errors (with “Unexpected ‘ignore’“):

	try {
		...			
	} catch (ignore) {
		alert('there was an error');
	}

Personally I think this is a great idea, it makes the code much more obvious. I’m going to start doing this in other languages too.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: