14 April 2012

Java Checked Exception and RuntimeException


Java provides two main exception types:
  • Runtime Exceptions :Runtime exceptions extend from either java.lang.RuntimeException or java.lang.Error.
  • Checked exceptions. All checked exceptions extend from java.lang.Exception
Runtime exceptions
  • The method signature does not need to declare runtime exceptions
  •  Caller to a method that throws a runtime exception is not forced to catch the runtime exception
  •  Runtime exceptions extend from RuntimeException or Error
Checked exceptions:
  •  method must declare each checked exception it throws
  •  caller to a method that throws a checked exception must either catch the exception or throw the exception itself
  •  Checked exceptions extend from Exception
Checked exceptions indicate an exceptional condition from which a caller can conceivably recover. Runtime exceptions indicate a programmatic error from which a caller cannot normally recover.

Checked exceptions force you to catch the exception and to do something about it. You should always catch a checked exception once you reach a point where your code can make a meaningful attempt at recovery. However, it is best not to catch runtimeexceptions. Instead, you should allow runtime exceptions to bubble up to where you can see them.

No comments:

Post a Comment