Friday, 29 November 2013

Exception handling in Java :



The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the runtime errors so that normal flow of the application can be maintained. An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:

   - A user has entered invalid data.

   - A file that needs to be opened cannot be found.

   - A network connection has been lost in the middle of communications or the JVM has run out of memory.



Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. Java exception handling enables your Java applications to handle errors sensibly. Exception handling is a very important yet often neglected aspect of writing robust Java applications or components. When an error occurs in a Java program it usually results in an exception being thrown. How you throw, catch and handle these exception matters. There are several different ways to do so. Not all are equally efficient and fail safe. 

To understand how exception handling works in Java, you need to understand the three categories of exceptions :

   1. Checked exceptions : A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time. 

   2. Runtime exceptions : A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation. The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. 

   3. Errors : These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Exception Hierarchy :

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.

Exceptions Methods :

Following is the list of important medthods available in the Throwable class.

SN Methods with Description

1 public String getMessage()      Returns a detailed message about the exception that has occurred. This message is  initialized in the Throwable constructor.

2 public Throwable getCause()     Returns the cause of the exception as represented by a Throwable object.

3 public String toString()        Returns the name of the class concatenated with the result of getMessage()

4 public void printStackTrace()   Prints the result of toString() along with the stack trace to System.err, the  error output stream.

5 public StackTraceElement[]getStackTrace()  Returns an array containing each element on the stack trace. The  element at index 0 represents the top of the call stack, and the last element in  the array represents the method at the bottom of the call stack.

6 public Throwable fillInStackTrace()    Fills the stack trace of this Throwable object with the current stack  trace, adding to any previous information in the stack trace.

Catching Exceptions :

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try
{
   //Protected code
}catch(ExceptionName e1)
{
   //Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

finally block :

The finally block is a block that is always executed. It is mainly used to perform some important tasks such as closing connection, stream etc. The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax:

try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}finally
{
   //The finally block always executes.
}

The throws/throw Keywords :

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords. The throw keyword is used to explictily throw an exception. We can throw either checked or uncheked exception. The throw keyword is mainly used to throw custom exception.

Declaring you own Exception :

You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes:

   - All exceptions must be a child of Throwable.

   - If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.

   - If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below:

class MyException extends Exception{ }

You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

Common Exceptions:

In Java, it is possible to define two catergories of Exceptions and Errors.

   - JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException,

   - Programmatic exceptions: - These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalStateException.


Exception handling in Java, Exceptions Methods, try/catch/finally blocks in Exception handling.

-- 
Regards,

Preeti Bagad [BE(CS)] 
SW Engineer Cum Blogger

On Line Assistence :
Y! Messenger : PreetiB.A1Soft@yahoo.com



15 comments:

  1. this is really helpful to the java professionals..
    6 Month Training

    ReplyDelete
  2. great article....
    find study material here
    GTU Study Material
    http://www.gtustudymaterial.in/

    ReplyDelete
  3. This Training has explain for Java Handling process of Java programming. Given the programming has easy step by step process of materials.

    dotnet training in chennai

    ReplyDelete
  4. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.

    PPC Services in Chennai

    ReplyDelete
  5. awesome way to get exert tips from everyone,not only i like that post all peoples like that post,because of all given information was wonderful and it's very helpful for me.

    SEO Company in Chennai
    SEO Services in Chennai

    ReplyDelete

  6. Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too.


    Manual testing training in Chennai


    Selenium testing training in Chennai

    ReplyDelete
  7. Very impressive post you have to share here with us, very informative.
    Genesis Technologies is one of the best IT company in Indore. We have developed a product accounting software development
    which is completely best in it's environment.

    ReplyDelete
  8. wow amazing post.The key points you mentioned here related to maintenance of car is really awesome.Checking all fluid levels,changing oil and of course the regular service of the car which is necessary to maintain our vehicle.Thank you for the information.

    bike spa services in mumbai
    house cleaning services in mumbai
    car wash services in mumbai

    ReplyDelete
  9. yes good description about object,exceptions and errors it will be remember to me,but i want more information from this topic.
    Back to original

    ReplyDelete
  10. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your.
    Digital Marketing Company in India

    ReplyDelete
  11. Thanks for this blog. provided great information. All the details are explained clearly with the great explanation. Thanks for this wonderful blog. Step by step processes execution are given clearly.Know the details about different thing.
    Web Development Company in India

    ReplyDelete
  12. Great site for these post and i am seeing the most of contents have useful for my Carrier.Thanks to such a useful information.Any information are commands like to share him.

    digital marketing company in india

    ReplyDelete