Wednesday 5 December 2012

Basics- Exceptions in Java




 

 

 

 

What are Exceptions?



Exception is the way to indicate an abnormal error that occurred in the called method.



Exception Handling:


  • When an error occurs within a method, the method creates an exception object and hands it off to the runtime system. The Exception object holds the information on the error, its type and state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
  • After a method throws an exception, the runtime system attempts to find a block of code (Exception Handler) to handle it.  The block to handle is searched  in the call stack.The exception handler chosen is said to catch the exception.
  • If the runtime system  searches all the methods on the call stack and doesn’t find an appropriate exception handler,  the program terminates. 

Exception Handling:

A block of code that can catch and handle the exception.   Mostly has the try.. Catch.. Finally block In the call stack when an exception is thrown,the appropriate handler for the exception will be searched towards bottom of the stack

Types of Exceptions:

There are 2 major category of Exception classes. Checked and Unchecked Exceptions. Below is the high level hierarchy of exception classes


Differences between Checked and unchecked Exceptions


Unchecked Exceptions
Checked Exceptions
Type
Runtime Exceptions
Compile time exceptions
extends
Subclasses of Error and RuntimeException
Subclasses of Throwable and Exception other than RuntimeException
throws
Donot need throws
Need appropriate throws
Exception handling
Do not mandate try catch
Mandate try catch somewhere in the call stack
Example
 OutofMemoryError, NullPointerException
ClassNotFoundException


Exception Hierarchy:


java.lang package hosts the exception classes in java.  As seen above, the 2 types of Throwable Error and Exception Hierarchy is shown in the below snapshot


 

Conclusion:


More basic details on Exceptions, handling and java.lang classes are covered in this post. More advanced information about creating Exceptions, handling exceptions with examples, Best practices will be covered in the next post.

No comments:

Post a Comment