beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Exception handling in java with examples

By Chaitanya Singh | Filed Under: Exception Handling

Exception handling is one of the most important feature of java programming that allows us to handle the runtime errors caused by exceptions. In this guide, we will learn what is an exception, types of it, exception classes and how to handle exceptions in java with examples.

What is an exception?

An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message. The good thing about exceptions is that they can be handled in Java. By handling the exceptions we can provide a meaningful message to the user about the issue rather than a system generated message, which may not be understandable to a user.

Why an exception occurs?

There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc.

Exception Handling

If an exception occurs, which has not been handled by programmer then program execution gets terminated and a system generated error message is shown to the user. For example look at the system generated exception below:
An exception generated by the system is given below

 Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:5)
 ExceptionDemo : The class name
 main : The method name
 ExceptionDemo.java : The filename
 java:5 : Line number

This message is not user friendly so a user will not be able to understand what went wrong. In order to let them know the reason in simple language, we handle exceptions. We handle such conditions and then prints a user friendly warning message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by user.

Advantage of exception handling

Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a program has bunch of statements and an exception occurs mid way after executing certain statements then the statements after the exception will not execute and the program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of program doesn’t break.

Difference between error and exception

Errors indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error.

Exceptions are events that occurs in the code. A programmer can handle such conditions and take necessary corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try to divide a number by zero this exception occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out of its bounds, for example array size is 5 (which means it has five elements) and you are trying to access the 10th element.

Exception classes hierarchy

Types of exceptions

There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions

I have covered this in detail in a separate tutorial: Checked and Unchecked exceptions in Java.

Checked exceptions

All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, you will get compilation error. For example, SQLException, IOException, ClassNotFoundException etc.

Unchecked Exceptions

Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

Compiler will never force you to catch such exception or force you to declare it in the method using throws keyword.

What topics are covered in the next tutorials

  1. Try-catch in Java
  2. Nested Try Catch
  3. Checked and unchecked exceptions
  4. Finally block in Java
  5. try-catch-finally
  6. finally block & return statement
  7. Throw exception in Java
  8. Example of throw keyword
  9. Example of throws clause
  10. Throws in Java
  11. throw vs throws
  12. Exception handling examples

Comments

  1. sravani says

    July 11, 2014 at 6:33 AM

    hi Chaitanya Singh,

    thanks for your efforts it is really appreciated.this is the best site i have ever seen. very clear explanation. please upload the frameworks also.then it will be very helpful to us.

    Reply
  2. Poornima says

    July 18, 2014 at 9:01 AM

    Explanation is good… Thanks

    Reply
    • akash says

      August 27, 2015 at 8:23 AM

      good reply

      Reply
  3. satyabrata barik says

    August 26, 2014 at 12:26 PM

    Hi Chaitanya,

    Thanks a lot for putting such hard work for us and I can say this is the most simplest website where the beginners really will be start focusing. It helped me and I usually go through your others subject when i get some time.

    Reply
  4. sampath says

    September 10, 2014 at 3:17 AM

    Am Lecturer in Computer Science, This site is an Excellent site. Very Good Explanation and easy understandable examples. very good. update frequently.

    Reply
  5. kumar vishal says

    October 29, 2014 at 3:53 AM

    Explanation is good.But, try to give more examples. Examples are so easy. For programming examples should be more for practices.

    Reply
  6. Harsh says

    March 12, 2015 at 6:02 PM

    Please tell me how to handle checked and unchecked exception with example?

    Reply
    • Ashfaq says

      November 16, 2015 at 12:15 PM

      Same mechanism is used to handle any exception. Difference between checked and unchecked exception is that if you don’t handle checked exception using try…catch block in your program then it will not compile.

      Reply
  7. Vikram says

    May 20, 2015 at 11:30 AM

    Hi,
    THis is very good site having explanation of core concepts in very simple manner.

    Regards
    Vikram

    Reply
  8. chandrasekhar says

    October 26, 2015 at 7:36 PM

    Hi Chaitanya,
    beginnersbook helped me a lot.Thank you.

    Reply
  9. Abhinav Kumar says

    December 3, 2015 at 6:50 PM

    Hi Chaitanya,

    Beginners Book is really one of the best to the ground sites for the basic JAVA learners.
    Thanks a lot for it…!!

    Reply
  10. hajra says

    January 25, 2016 at 12:59 PM

    thank you so much for a simple and clear explanation…

    Reply
  11. Nawal Sah says

    February 17, 2016 at 6:55 AM

    What is the difference between compiler error and exception?

    Reply
    • praveen says

      March 2, 2017 at 10:02 AM

      Compiler error:when we compile the program then we will get compile time error.

      Exception:an unwanted unexpected event disturbs the normal flow of the program execution.

      Reply
  12. Nawal Sah says

    February 17, 2016 at 6:57 AM

    What code block should we never return from and why?

    Reply
  13. Nawal Sah says

    February 17, 2016 at 7:02 AM

    What is Error? Can we catch Errors? If yes, what should be done in the catch block and why?

    Reply
  14. Chitra says

    September 9, 2016 at 7:49 AM

    thanks a lot.. it is nice blog to know the java concepts.. simple and easy yar… :)

    Reply
  15. Brian Wekesa says

    December 19, 2016 at 9:14 AM

    good work I enjoyed reading it……….#bryan

    Reply
  16. Sandor Szekeres says

    December 27, 2016 at 1:47 PM

    “When an exception occurs program processing gets terminated and doesn’t continue further.”

    It is not strictly true… If we handle the exception correctly then it can continue processing.
    Am I right?

    See the first exception of this article:
    https://beginnersbook.com/2013/04/try-catch-in-java/

    Reply
  17. Deepan says

    June 20, 2017 at 1:06 PM

    The way you have explained is really awesome, also you have provided the examples where ever required.

    thanks for your great effort.

    Reply
  18. Gajanan Kharat says

    September 1, 2017 at 6:33 AM

    Hello Chaitanya,

    Nice explanation about Exception handling but Could you please elaborate How ClassNotFoundException
    comes under the “Checked Exception”, I guess it should be unchecked exception

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Exception Handling

  • Exception handling
  • try-catch block
  • Multiple catch blocks
  • nested try-catch
  • finally block
  • Flow Control in try-catch-finally
  • throw keyword
  • throws clause
  • throw vs throws
  • Custom Exception
  • Checked and Unchecked Exceptions
  • Exception Examples

MORE ...

  • Java Tutorial
  • OOPs Concepts
  • Java String
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2019 BeginnersBook . Privacy Policy . Sitemap