Tuesday, August 24, 2004

Exceptions - another implementation difference

Good article on IBM developerworks regarding exceptions.

Another difference in implementation between Java and C#. Java has the checked vs unchecked exceptions. C# just has unchecked. The article does a good job of explaining the thinking behind each implementation.

The problem with checked exceptions is that you need to specify which exceptions you will catch in the method signature. It's a problem because since it's part of the interface, it is essentially set in stone. If ever you refactor the code in the method and those resulting new methods throw new exceptions, you will need to modify the method signature with the added exceptions, thus breaking compatibility. As you go higher up in the code hierarchy you need to make sure that your methods keep adding exceptions that could be thrown in the lower code.

The problem with the C# way is that since there is no information about what exceptions are thrown, you dunno what to catch. You have to rely on the documentation. It's not baked into the system.

There are pro's and con's to each way as is mentioned in the article. I personally don't have a clear opinion on which is better. One thing I read that made sense was that exceptions are supposed to be exceptional. If one is thrown, something is out of the norm. It shouldn't be silently ignored which might be the temptation with Java since you have to keep track at every level.

Overall, I feel there needs to be better literature out there regarding how exactly to handle exceptions in an application. Atleast, I haven't come across too many good articles. As we had discussed before, it doesn't seem right when there are a whole bunch of try catch blocks in your code. It's not the right way.

No comments: