Java vs. C# - Part 3 - Exceptions

Java vs. C# - Part 3 - Exceptions
   Here is part 3 of the Java vs. C# series which should have been called "Why C# Is Better Than Java". I remind you to read part 0 in order to get familiar with the motivation behind the articles. Part 1 and part 2 are also recommended.

   If I have to pick the single worst flaw in the Java language design it would be the inclusion of checked exceptions (It would be a tough fight with the primitive types though). If Java was one of these pure functional languages where functions are not allowed to have any undeclared side effects I would be the first to support checked exceptions because the truth is that exceptions are part of the function's return type and should be declared somehow in the signature. However Java is not anything like Haskell and in Java checked exceptions are actually evil. The problem is that they provoke undisciplined, lazy or incompetent developers to write even worse code while providing no additional value to good developers.

   How do they provoke bad code? When a lazy developer is forced to catch an exception that he does not need to catch what he does is write an empty catch. This is far worse than forgetting to catch an exception when it needs to be caught because it is covering an error. Things get even worse when someone is forced to catch multiple exceptions. This is when a bad developer is likely to catch Exception in an empty catch and cover all exceptions not only the checked ones. This is known as Pokemon Exception Handling or as I like to call it - defeating the exceptions. To make matters worse it is hard to judge whether a method should throw checked or runtime exception even for an experienced developer. I believe frameworks like Spring and Hibernate even wrap some of Java's checked exceptions into runtime exceptions.

   To be honest there is some value in checked exceptions namely they serve as documentation. While having documentation is undoubtedly useful the idea that the compiler should enforce the presence of documentation does not feel right to me. What is more I do not see any reason why possible runtime exceptions should not be listed in the documentation and why it cannot happen automatically. It seems to me that the compiler can easily write runtime exceptions in the method metadata and copy this information into calling methods when they are compiled. I wonder why compilers do not this. If anyone knows please let me know.

   If documentation is helpful why do I claim that it does not help good, disciplined developers write better code? Firstly because good, disciplined developers write documentation and read documentation (at least the JavaDoc/XML comments). The good developer will handle the cases that require checked exceptions anyway but what is he going to do if he knows an exception cannot occur? He is going to wrap it in a runtime exception of course but why force him to write code that nobody needs instead of throwing a runtime exception in the first place? What about exceptions that always need to be caught? Well in my opinion they do not exist. One reason is that methods have input and output and represent a functional dependency. What if I programmatically generate all the input? In this case I can be absolutely sure that I will not get an exception. However in some cases you cannot control all of the input for example if the method calls into a system you do not control (or in the lighter case if you control it indirectly as is the case with databases). While this case is definitely more reasonable than the simple input validation case there is still a problem with it. Checked exceptions assume that the system that is supposed to catch them can recover from the exception and often this is not the case. It is a bad practice to catch exceptions from which the system cannot completely recover. In this case the exception should be rethrown through the entire stack right to the main method which effectively turns it into an annoying special case of runtime exception.

   Checked exceptions have proven a burden to the language now when the designers are trying to add lambda expressions (a.k.a. closures) because they are actually methods that can throw a checked exception. The good news is that a number of people are suggesting that checked exceptions should be removed from the language and one day this can happen. Backward compatibility will be preserved because really there is nothing special about checked exceptions at runtime.

   In an interview on checked exceptions with Anders (Hallowed be His name!) himself. He makes a point about versioning that I do not completely agree with. He claims that checked exceptions are bad for versioning because when a method adds new features it might throw new exceptions which will break existing clients. At first it looks like a good thing but as Anders (Hallowed be His name!) points out this is not always the case because most exceptions are actually unhandled and this is how it should be.  I am not sure if the tradeoff between informing the developers and not breaking the code is in favor of runtime exceptions but at best the match is even and in a good language design you do not add a feature to trade one problem for another.

   Oh and if you did not know before reading this article you probably already know how C# solves the checked exception problem. It does not have them.

   Well this is all for now. I cannot think of any other language design flaws in Java that are worth of an article. As I pointed out earlier it would be unfair to list features that C# has and Java lacks before Java 7 is released. I hope that you the readers learned something about language design from these articles or at least learned how to avoid misuse of certain features.
Tags:   english programming 
Posted by:   Stilgar
14:29 15.07.2010


First Previous 1 Next Last 

Posted by   JOKe (Unregistered)   on   17:49 15.07.2010

Will paste my explanation on more than 1 comment because there are some stupid limits for 50 new brakes and 1000 symbols in one comment.

Posted by   JOke (Unregistered)   on   17:49 15.07.2010

I will give as always the fallowing example:
lets suppose Petar is a stupid developer... and he is a C# developer... let say I and petar have something in common - WE NEVER WRITE DOC or ANY other SHITS cuz we dont have good english.
lets suppose Petar has made a totally awesome method which makes everything .. basiclly a "solve my problem" method or just to keep it simple it will be sayTapak(string name) yes it is say Tapak and when the method is called it uses the argument 'name' and says that name is tapak. This method ofcourse is encrypted obfuscated whatever putted in dll totally restricted and this method maybe cost a big amount of money. And after all we dont see the code which "SHOULD" be something like return "Tapak "+name;
scenarion 1:
4o4o which is also a stupid C# developer and 4o4o found the great awesome sayTapak method which was written by Petar.
so 4o4o write the fallowing code:
sayTapak("mun4o"); -> mun4o is tapak
sayTapak("ivan"); ivan is tapak
enough testing lets use it.
so .. this library is used happily and putted in 500 000 euro project.
life's good everybody is happy BUT one day.. a client with the name Petar has come and the sayTapak method has been invoked...
[RUNTIME EXEC] sayTapak("Petar"); -> BLAH BUF PetarIsNotTapakException BUF pras restart the IIS BUF  fuck pras .. dial ringgg a bug ringgg OMG .. fuck money fuck fuck extra fuck anyway.
so why this has happened ?
because the origianl Developer Petar has writen ( sorry for the crapy C# syntax maybe it is incorrect )
public string sayTapak(string name){
if(tapak=="Petar") throw new PetarIsNotTapakException();//undocummented feature.
return "tapak "+name;
cool... thats why C# rox.. we have a lot more money to spend to fix the bug and a lot of fucking which is nice I guess.

Posted by   JOKe (Unregistered)   on   17:50 15.07.2010

what will happen in a nice java world that everyone is singing songs and playing cards and watching sc2 replays on youtube all day.
lets assume that Petar is a Java developer.. who is also stupid and also not writing ANY documentation.
so Petar has created exactly the same method.. the problem is that this exception should be mentuned in the implementation of the method at language level not just a doc level. So the Java implementation will be :
public String sayTapak(String name) throws PetarIsNotTapakException{
if(tapak=="Petar") throw new PetarIsNotTapakException();//undocummented feature, BUTthere is a throws in the method signiture.
return "tapak "+name;
so lets suppose that 4o4o want to use this great library which is probably not obfuscated and not in dll and not closedsource and probably 4o4o have a nice decompiler but ANYWAY lets say it is FORBIDEN to be SEEN ! so.
4o4o is trying to write the fallowing code.
sayTapak("4o4o"); ->> before compile even eclipse will say SORRY DUDE YOU HAVE TO CATCH THE EXCEPTION... oki CTRL+1[ENTER]
and the code is magically translated to :
try {
} catch(PetarIsNotTapakException e){
afcourse 4o4o has changed that method to:
try {
} catch(PetarIsNotTapakException e){
//ignore I have no idea what this excpetion is about so lets just warn
logger.warn("soem strange exception happened when I invoked the sayTapak with input 4o4o",e);
and ... the project for 250 000 has been created ( the amount is smaller because they dont pay for MS SQL, IIS, WinShit, Stupid developers) SO one day a new client came.
Petar was his name... he try to login or register or anyway and :
[RUNTIME EXEC] sayTapak("Petar"); --> logged exception nothing happens ... maybe there will be some indication to the user maybe not.. hmm oki lets try than with Pesho
[RUNTIME EXEC} sayTapak("pesho"); --> Pesho is tapak
cool than it is working maybe a little bug anyway lets continue work and watch replays on SC2, or porn or soccer depends :D
so checked exceptions halps to be more lazy to have more time for sc2 to save money ( also java helps for that ) and to not loose a big amount of money because of stupid C# developers.

Posted by   JOKe (Unregistered)   on   17:50 15.07.2010


Posted by   Stilgar   on   18:17 15.07.2010

catch(PetarIsNotTapakException e){
//ignore I have no idea what this excpetion is about so lets just warn
logger.warn("soem strange exception happened when I invoked the sayTapak with input 4o4o",e);

And this is remarkably bad code that only ignorant Java developers believe is better than the yellow page of death (for example). I will not try to explain once again why it is bad code because if the article itself and the three external articles linked are not enough to explain why I think it is hopeless.

Posted by   ivelinka   on   18:34 15.07.2010

JOKe your explanation is very good:))) but instead of defending checked exceptions it proves one more time that they are bad. Hiding the exception doesn't make the application better. It causes even more problems to the developers and it makes it difficult for them to find the problem. You are right that it is better to log the exception than leave an empty catch but still to see the exception is even better. When in production most applications have error screens so that user don't see the exception but an error page so it is still ok to throw an exception. The users can help you reproduce it and you can easily find it by the stack trace.

Posted by   JOKe (Unregistered)   on   18:41 15.07.2010

Stilgar I said that all developers in my examples are stupid so there is no good code written by them. As you know most good projects which cost a lof of money are made by stupid companies and stupid developers. So as I said I am not saying that ignoring exception is better I am just saying that if something which doesnt need to crash the whole system has happened than just log it or show a popup to the user and thats it, never forget it. Cuz in a normal situation this method will be in a BIG library which cost 20k euro and if there is a bug or something like that that should be fixed it takes ages you need update so another 3k and etc also you need a consultant to exaplin yuo why the fuck this exception is thrown, when I pass Petar

Posted by   Ivelina (Unregistered)   on   18:48 15.07.2010

in my example the exception is logged so all developers should recieve a email with the whole exception stacktrace (I was passing the exception object to the logger ) the user dont care about the stacktrace or WHAT is a stacktrace ;)

Posted by   JOke (Unregistered)   on   18:48 15.07.2010

ups last one was from me ... for ivellina :DD sorry :DD I am sleeping :DDD

Posted by   ivelinka   on   18:52 15.07.2010

JOKe one time a colleague of mine received the following task:
Please take this log (size: <some big number> MB) and examine all logged errors and examine when and why they appeared.

Do you mean this kind of mail?:)

Posted by   Stilgar   on   19:00 15.07.2010

Just login so you won't have to type your name.

In every example the exception is logged. When you see the error page the exception is still logged (like all other exceptions). It is far better to have one general unexpected error handling behaviour than letting the user continiue to use the system with the broken state (i.e. he has Petar typed in that textbox!) that can break your data and do irreversible damage.

Posted by   JOKe (Unregistered)   on   19:55 15.07.2010

If you have an error page for unhandled exceptions. what if it is a console app ? or an desktop app ? or a workflow app ? or silverfight app or WFPFCSR app ?

Ivelinka: thats because you have stupid team leaders :)
the log4j have an email appender out of the box you just have to specify all emails that should recieve an email when error appear ( this is mostly happening durring validation phase ) so basiclly each email is max of 500k long and contains the stacktrace ( sometimes the URL also )

Posted by   ivelinka   on   20:02 15.07.2010

JOKe actually we they one time activated the notification but the mail server blocked it because of flood filter! So... no thanks:) I prefer having the error page where the user submits a ticket and it is later discussed and assigned to me to fix including the steps to reproduce.

Posted by   Stilgar   on   20:15 15.07.2010

Console apps are supposed to return errors to the caller. Desktop apps should display an error message and return to the last known good state. Workflow apps are pretty much console apps and Silverlight apps are desktop apps. You should not allow an application with a corrupted state to continiue running. If Windows allowed the system to continue running when there are critical errors instead of showing a BSOD there would be a lot more broken hardware and even computers on fire. If the app costs a lot of money chances are the damage from corrupting the data would be proportional.

Posted by   Guest (Unregistered)   on   20:46 14.01.2011


Posted by   Guest (Unregistered)   on   20:46 14.01.2011


Posted by   Stilgar   on   21:50 14.01.2011

I am stunned by the quality of the comments by the guest above.

First Previous 1 Next Last 

Post as:

Post a comment: