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:

   //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:

   //Protected code
}catch(ExceptionType1 e1)
   //Catch block
}catch(ExceptionType2 e2)
   //Catch block
}catch(ExceptionType3 e3)
   //Catch block
   //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.


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

On Line Assistence :
Y! Messenger :


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

  2. great article....
    find study material here
    GTU Study Material

  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

  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

  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


  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

  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.

  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

  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

  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

  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

  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

  13. This article provides the information about Java its key features and scope for java professionals. This information is really helpful me to know more about Java programming language.
    Java Training in Chennai | Java Training | Java Course in Chennai

  14. Thanks for sharing this information and keep updating us. This is informative and really useful for me.

    JAVA Training Institute in Delhi | Network Training Company in Delhi | Software Testing Training In Delhi

  15. Awesome, Very Informative Post. I really enjoyed with this article here. it wish that it help for beginner.

    Best Hadoop Training in Gwalior | Best Big Data Training in Gwalior | Best CCNA Training in Gwalior

  16. This article provides the information about Java its key features and scope for java professionals. This information is really helpful me to know more about Java programming language.
    Training institute

  17. Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point. | |

  18. Really it was an awesome article...very interesting to read..You have provided an nice article....Thanks for sharing..
    Best website developers in bangalore
    Outsource magento ecommerce services india

  19. Fertility is the natural capability to produce offspring. As a measure, fertility rate is the number of offspring born per mating pair, individual or population.Human fertility depends on factors of nutrition, sexual behavior, consanguinity, culture, instinct, endocrinology, timing, economics, way of life, and emotions.Greate thinks of a fertility center for humans.

    Fertility Center in OMR

  20. I do agree with all the ideas you have presented in your post. They’re really convincing and will certainly work. Still, the posts are very short for newbies. Could you please extend them a little from next time? Thanks for the post..
    Paper Publishing Sites
    Naas Rated Journals
    Language Translation Services
    Research Paper Writing Service
    Article Writing Services

  21. I have really happy to these reading your post. This product control and maintenance of our health.The daily routine can assist you weight lose quickly and safely.My life is completely reworked once I followed this diet.I feeling nice concerning myself.

    Herbalife in Chennai
    Nutrition centers in Chennai
    Weight Loss in Chennai
    Weight Gain in Chennai

  22. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts, have a nice weekend!
    Digital Marketing Training in Chennai

  23. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
    Thanks for sharing
    java training in chennai
    java training in bangalore
    java online training
    java training in pune

  24. Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.

    Digital Marketing Course in Chennai
    Digital Marketing Training in Chennai
    Online Digital Marketing Training
    SEO Training in Chennai
    Digital Marketing Course
    Digital Marketing Training
    Digital Marketing Courses

  25. wow great info. i am sure i will share this to my friends and relatives. Thank you very much.

    Oneplus Service Center in Chennai

  26. All the latest updates from the Python Automationminds team. Python Automationminds lets you program in Python, in your browser. No need to install any software, just start coding straight away. There's a fully-functional web-based console and a programmer's text-editor
    Phyton training in Chennai

  27. nice work keep it up thanks for sharing the knowledge.Thanks for sharing this type of information.
    digital marketing company in delhi

  28. nice topic which you have choose.
    second is, the information which you have provided is better then other blog.
    so nice work keep it up. And thanks for sharing.
    Epoxy Grout manufacturer in delhi


  29. Nice blog..! I really loved reading through this article. Thanks for sharing such a amazing post with us and keep blogging...Well written article ------- Thank You Sharing with Us Please keep quiz questions and answers | android code best practices
    android development for beginners | future of android development 2018 | android device manager location history

  30. We are happy now to see this post because of the you put good images, good choice of the words. You choose best topic and good information provide. Thanks a sharing nice article.

    Digital marketing company in delhi


  31. hi, nice information is given in this blog. Thanks for sharing this type of information, it is so useful for me. nice work keep it up. digital marketing company in delhi

  32. Thanks for giving great kind of information. So useful and practical for me. Thanks for your excellent blog, nice work keep it up thanks for sharing the knowledge.
    Thanks for giving great kind of information. So useful and practical for me. Thanks for your excellent blog, nice work keep it up thanks for sharing the knowledge.

  33. This is extremely great information for these blog!! And Very good work. It is very interesting to learn from to easy understood. Thank you for giving information. Please let us know and more information get post to link.
    datapower training

  34. nice topic which you have choose.
    second is, the information which you have provided is better then other blog.
    so nice work keep it up. And thanks for sharing. Laminated Doors manufacturer in hubli

  35. Thanks for giving great kind of information. So useful and practical for me. Thanks for your excellent blog, nice work keep it up thanks for sharing the knowledge. led lawn lights in delhi

  36. Good job! Fruitful article. I like this very much. It is very useful for my research. It shows your interest in this topic very well. I hope you will post some more information about the software. Please keep sharing!!
    SEO Training Center in Chennai
    SEO Institutes in Chennai
    SEO Course Chennai
    Best digital marketing course in chennai
    Digital marketing course chennai
    Digital Marketing Training Institutes in Chennai

  37. I am really enjoying reading your well-written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.
    SEO training course
    Best SEO training in chennai
    SEO Training Center in Chennai
    Digital Marketing Training
    Digital marketing training institute in chennai
    Digital marketing classes

  38. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition.
    nebosh course in chennai

  39. Nice blog has been shared by you. it will be really helpful to many peoples who are all working under the technology. Thank you for sharing this and safety course in chennai

  40. Hi dear, This is an nice and valuable post thanks for this information! Visit for lifestyle way at
    Lifestyle Magazine India

  41. A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one.I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts read this.
    Java training in Chennai

    Java training in Bangalore

  42. I am amzaed by the way you have explained things in this post. This post is quite interesting and i am looking forward to read more of your posts.
    Find the Interior Designers in Vijayawada

  43. I am waiting for your more posts like this or related to any other informative topic.
    ibm integration bus training
    ibm message broker training

  44. This is very helpful for who wants to learn professional Education.
    Devops Training
    Dotnet Training

  45. Our line by line lyrics generator is great for writing and fine-tuning songs and raps, especially when you want them to rhyme. Unlike our other song lyrics.


  46. بسم الله الرحمن الرحيم تقدم لكم شركة الكمال جميع خدمات رش المبيد يجميع انحاء المملكة بافضل انواع

    المبيدات للقضاء على جميع الحشرات الطائرة والزاحفه كالصراصير والفائران والنمل الابيض والبق

    والذباب والناموس
    شركة رش مبيدات بالطائف
    شركة رش مبيدات بجازان
    شركة رش مبيدات بحائل
    والسلامه عليكم ورحمة الله وبركاته