Thursday, 8 March 2012

Exception Handling in Java

Exception and Exception Handling:

•An exception is a run-time error. Exception can also be defined as an abnormal or unexpected condition that’s occurs at run-time (when executing the program).
•Handling exceptions is known as Exception Handling.


Exception Handling Fundamentals:

•A Java Exception is an object that describes an exceptional condition that occurs at run-time in a piece of code.
•When an Exception occurs in a method, the Exception must be thrown by the method. The method may or may not handle the Exception.
•Exceptions can be generated by the Java run-time system or manually generated by the code in the program.
•Exceptions generated by the Java run-time system are handled by the Java run-time itself.
•Manually created exceptions must be handled by the programmer.

•Java provides five keywords for exception handling. They are:
1) try
2) catch
3) throw
4) throws
5) finally


•try: Any statements that may raise an exception are included in the “try” block. Every “try” block requires atleast one “catch” or “finally” block.
•catch: The exception handling code is provided in the “catch” block.
•throw: System-generated exceptions are thrown by the Java run-time system. Manually generated exceptions must be explicitly thrown. This is achieved by using the keyword “throw”.
•throws: All the checked exceptions that are thrown must be mentioned with the keyword “throws”.
•finally: Any code that must be executed whether or not an exception occurs is written in the “finally” block.



Exceptions Hierarchy:
Exceptions Hierarchy



•All the exceptions in Java, are the subclasses of the class “Throwable”. It is the root class in the exceptions hierarchy.
•“Throwable” contains two subclasses, “Exception” and “Error”.
•“Exception” subclass contains all the exceptions which are generated by the code in the programs.
•“Error” contains all the exceptions that are generated by the Java run-time system.

No comments:

Post a Comment