Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/nebupook/public_html/include.database.php on line 2

Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 32

Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 33

Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 32

Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 33

Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 32

Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 33

Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 32

Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 33
NebuPookins.net - NP-Complete - Java's checked exceptions vs unchecked exceptions
 

Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 32

Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 33
Java's checked exceptions vs unchecked exceptions
[Computer]

Java programming post here folks, so if you're not into that kind of stuff, well, too bad. The topic is when to use checked exceptions versus unchecked exceptions. I'll start with a little background, in case you're not familiar with these two concepts. If you are familiar (or just don't give a damn), feel free to skip the next 5 paragraphs (or this whole post).

There's a class in the J2SE API called Exception, and there's a class called RuntimeException. Both of these classes are "magical" in the sense that the Java language treats these classes in a special way compare to all other classes. In particular, in the "throw [expression];" statement, the expression must resolve to an object of type Exception.

Exceptions, as the name implies, are used to indicate exceptional situations for which your code can't handle. For example, you might write a code which loads the a map for use in a game from a file to memory. Your function takes a filename as input, and is supposed to return a datastructure representing the map as output. Let's say you're given a filename and you find out that the file that the filename refers to does not exist. There's not much you can do about this situation. You can't just show a "File not found" error message box, because making this method isn't being called in a graphical environment with a windowing system; maybe your method was called by a utility which tries to compressed maps by removing inaccessible areas for example, which was only run in a console. You can't print "File not found" to the console, because maybe your method is being run in a full screen game to which the console isn't visible. Basically, you're not in a position to handle this exception, so you should "throw new FileNotFoundException(filename);"

FileNotFoundException is a class that's defined in the J2SE API whose purpose is to indicate the exceptional situation of not being able to find a particular file. The J2SE API defines a bunch of exceptions that may be useful for various purposes. FileNotFoundException is a subclass of Exception. Note that it's not a subclass of RuntimeException. Because it's not a subclass of RuntimeException, it's referred to as a "checked exception". This is because if you write a method which throws any Exception which is not a subclass of RuntimeException, then whoever runs your method must "check" for this exceptional condition. So if you wrote the above map loading routine, you have to add the keywords "throws FileNotFoundException" in the method declaration. When I try to use your method, I'll immediately see these keywords and know that there's an exception that I have to check for.

In this case, I have two choices. I can either pass the buck by putting those same keywords in my code, so that whoever the next guy is who's using my code knows that he has to check for this exception; or I can try to actually handle the exception myself. An example of when I might want to do the former is maybe my code is a resource manager which tries to cache objects in memory so that you don't need to read from the DVD that the game maps are stored on so frequently; in this case, I still don't know if I'm running in a graphical environment or not, so I too cannot handle this exception. The latter case might be when I'm actually writing code for a map editor. In this case, I know I'm in a windowing system, because the map editor requires a mouse and GUI to use, so I know the appropriate thing to do is display a pop up box explaining to the user that the filename they entered in doesn't refer to an file that actually exists.

RuntimeExceptions are "unchecked", meaning you don't have to put the "throws [whatever]" clause in your method declaration, which means if I use your method declaration, I won't know that your method might throw an exception. I claim this is bad, because if your method throws an unchecked exception, and I don't handle it, then the Java system will automatically make my method rethrow that same unchecked exception, passing the buck up to a higher level, in hopes that someone will eventually handle it. If the exception reaches all the way to the top and no one handles it, then the whole program just crashes. Given that no one had any idea that there were an unchecked exceptions to handle in the first place, it's very likely that no one's going to write code to handle the unchecked exceptions. So basically I'm sayign unchecked exceptions are bad and lead to buggy code.

So if it's bad, why did Sun invent the concept of unchecked exceptions at all in their code? Because it's something that's useful internally in the java system. Consider the ArithmeticException class. That's a subclass of RuntimeException, which means ArithmeticException is an unchecked exception. Sun designed it this way on purpose so as not to annoy Java programmers. In theory, an ArithmeticException could occur every time an arithmetic operation might occur. If you have the statement "z = x + 1;", meaning assign to Z the value of X + 1, this might lead on an Arithmetic Exception. Why? Perhaps X is so big that it's the biggest number that the computer can represent. Try to add 1 to it and you get an integer overflow. If ArithmeticException were a checked exception, that means we'd either have to add code that checks that the arithmetic operation we perform didn't fail every time we do any arithmetic operation at all, or we'd have to "pass the buck" and declare that we're throwing ArithmeticExceptions every time we perform an arithmetic operation in our code. Neither option is very appealing.

As my friend Zahlman put it, a RuntimeException typically arises in situations where you make a mistake somewhere in your code. That means you're not expecting this exception to ever get thrown (even though it might), and if you don't expect the exception, you can't think of a rational way to handle it.

Contrast this with a checked exception. A checked exception means occurs when there is nothing wrong with your code, but you're simply in a situation you can't handle (e.g. given a wrong filename). So you document this fact by placing the "throws" keyword in your method which basically says "There are a few situations where my code won't work (e.g. file not found), so please take care of these situations for me." This is much more preferable that using unchecked exceptions which basically say "Don't worry, this code is foolproof!" and then later, when it crashes, apologize "sorry guys, I fucked up."

All of this to say, when you're designing a new type of Exception to be thrown (for example, let's say your game requires that every map have exactly two bases, one for the red team and one for the blue team, and you want your map loading code to check these requirements, to prevent cheaters from hacking a map file so that only one of the two teams has a base; so you make a MapDoesntHaveTwoBaseException) make sure you make it a checked exception, and not an unchecked one.

Writing unchecked exceptions is basically writing malicious code designed to mislead its users, whereas writing checked exceptions is clearly indicating that there are some situations your code can't handle, which will allow the user to be more informed about what code to use in her product.

 
Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 60

Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 61
E-mail this story to a friend.
1. jaybose said:
The real purpose of of an unchecked exception is make the life of a developer easier. The java spec gives a good example. http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html#44149
Posted on Mon July 18th, 2005, 9:29 AM EST acknowledged
2. Nebu Pookins said:

Hi Jaybose, thanks for posting on my blog.

For example, certain code might implement a circular data structure that, by construction, can never involve null references; the programmer can then be certain that a NullPointerException cannot occur, but it would be difficult for a compiler to prove it.
Java Language Specifications, 2nd Edition

The example that the Sun gives is that sometimes the developer knows a NullPointerException will never occur, but the compiler can't prove this. It would be a hassle to catch that exception if it never occured, so Sun makes that Exception a unchecked one.

As I mentioned in the post above, unchecked exceptions are "useful internally in the Java system." Sun's example fits with my explanation: It's the compiler that doesn't know whether an operation is safe or not, so it wants to have the freedom to throw an exception just in case.

However when you, as a human programmer, write code, you either know of an exceptional condition that your method can't handle, or you can't think of any such condition. If you know of an exceptional condition that your method can't handle, declare your method as throwing that exception, and make sure it's a checked exception, so that people using your method are fully aware of the implications of using your method.

If you can't think of any exceptional condition which your method can't handle, then don't declare it as throwing anything.

Posted on Mon July 18th, 2005, 4:56 PM EST acknowledged

You must be logged in to post comments.

Sites linking to this post: