Monday, November 16, 2009

Java Checked vs Unchecked Exception

Some guidelines about check and uncheck exception:
  • Only exceptions that will cause a method to complete abruptly should appear in its throws clause.
  • There are two kinds of exceptions in Java, checked and unchecked, and only checked exceptions need appear in throws clauses.
  • Any checked exceptions that may be thrown in a method must either be caught or declared in the method's throws clause.
  • Whether or not an exception is "checked" is determined by its position in the hierarchy of throwable classes.
  • To create a new checked exception, you simply extend another checked exception. All throwables that are subclasses of Exception, but not subclasses of RuntimeException are checked exceptions.
  • Most unchecked throwables declared in java.lang (subclasses of Error and RuntimeException) are problems that would be detected by the Java virtual machine.
  • Errors usually signal abnormal conditions that you wouldn't want a program to handle.
  • If you are throwing an exception to indicate an improper use of your class, you are signalling a software bug. The class of exception you throw probably should descend from RuntimeException, which will make it unchecked. Otherwise, if you are throwing an exception to indicate not a software bug but an abnormal condition that client programmers should deal with every time they use your method, your exception should be checked.
  • At least one clause, either catch or finally, must be associated with each try block. If you have both catch clauses and a finally clause with the same try block, you must put the finally clause after all the catch clauses

2 comments:

ArrayList Example Java said...

Good post. Indeed Checked exception is one of the most criticized feature of Java specially for its boiler plate handling code which cluttered the code. Though Java7 provides some relief by adding automatic resource management and support for handling multiple exception in one catch block. If not using java7 you can still wrap your checked exception into Unchecked one.

Anonymous said...

Good recommendation "ArrayList Example Java", thanks for sharing the links.