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.

2 Comments »

  1. You should NEVER do this in real life. Discarding errors just makes someone else’s (or your) life harder in the future.

    Comment by Chris K — January 29, 2021 @ 6:21 pm | Reply

    • I highly disagree with this. There are a bazillion reasons why ignoring an error makes sense. Why polluting the console or UI if the error is not needed in certain cases.

      Comment by Daneil — February 11, 2022 @ 11:06 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.