Java Exceptions Tutorial

Exception in Java is used to handle errors or any other exceptional event that occurs in the normal flow of a program. There are several way Exception can occur in Java.

  • Data provided is not in expected format(eg. int instead of String).
  • DB cannot be connected.
  • Network connection Lost.
  • An object is null.
  • …..

Java Exception Hierarchy

Every Exception in Java is the subtype of Exception class which in turn is the subclass of Throwable. And as we know everything in Java derived from Object class Throwable also derived from class Object. Exception and Error are two different classes that derived from Throwable. Errors represent a situation which doesn’t occur because of Programming error but that might happen at the time of program execution and these are abnormal behavior which java program cannot handle and shouldn’t bother to handle. JVM running out of memory is a type of Error which can occur at runtime.

Checked vs UnChecked Exception

Checked Exception

  1. Checked exceptions are subclass’s of Exception excluding RuntimeException and its subclasses.
  2. Checked Exceptions force programmers to deal with the exception that may be thrown.
  3. When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action,or pass the exception on to its caller.

Example

IO exception.

Unchecked Exception

  1. Unchecked exceptions are RuntimeException and any of its subclasses.
  2. A compiler doesn’t force the programmers to either catch the unchecked exception or declare it in a throws clause.
  3. Programmers may not even know that the exception could be thrown.
  4. Checked exceptions must be caught at compile time.
  5. Runtime exceptions do not need to be.

Example

ArrayIndexOutOfBounds Exception.

Java Exception Handling

Now we know that exception can occur in Java program at any time(or Any Location). So we need to know how to handle these exceptions.  Handling exception is a required attribute in developing a robust application. Handling Exception means transferring execution of the program to appropriate handler when an exception occurs. We can handle the exception by using try-catch block.

try: try is used to define the block of code where an exception can occur.

catch: catch is used to match a specific type of exception. There could be more than one catch clause for one try block.

finally: finally determine a block of code which will always execute after the try block. Even in the case of Exception.

		try {
			throw new IOException();
		} catch (IOException e) {
			// Handle only IO Exception
			// This block will get executed only in case of IOException
		}catch (Exception e) {
			// Handle only all other type of exception
			// This block will get executed in case of all exception except IOException
		}finally{
			System.out.println("This block will get executed no matter exception occur or not");
		}

Note*: try clause cannot stand without a catch or finally block. Any of them is required.

Exception Propagation

It is not required to handle all exception thrown by try block in the catch block (As it is not required block). In case catch block doesn’t handle the exception thrown by try block, it will be propagated to the method where this method was called from. In case the previous method which called this method also doesn’t handle it, the exception will be propagated to the last method in method stack, and it will keep propagating in the same way unless some method handle it. In case none of the methods handle it in the call stack, the exception will reach to bottom and JVM will handle it.

(Thanks to Mohita for Suggestion)

 

Cheat-sheet

  • checked & unchecked exception are two type of Exception.
  • A checked exception is those exceptions which are the subtype of Exception class but excluding classes which extends Runtime exception.
  • A subtype of Error and Runtime Exceptions comes under unchecked Exception.
  • Finally block will always be invoked in all condition.
  • System.exit() is the only way when finally block will not get executed coz, in that case, JVM will shut down.
  • Custom Exception can also be created by extending Exception class.
  • Catch block should be ordered in the form of most specific to most general. Otherwise, the compiler will complain about unreachable code.

19 Comments Java Exceptions Tutorial

  1. Akhilesh

    you have been passing incorrect information, as per your example you have said ArithmeticException is checked exception however it is not. Refer below java implementation of the same class.

    public class ArithmeticException extends RuntimeException { }

    Please double check the content before you post them as many folks are trying to learn from it.

    Reply
    1. Vivekanand

      We are humans and we also do mistakes sometime. Though it was not intentional, Same has been corrected.

      Reply
      1. Muthu

        Last interview I was asked a question that, “”Write a User exception & Use that exception class to Login program “”
        i) In case Login is invalid use User define Exception

        Admin will yu pls answer for this one…:-(

        Reply
        1. Vivekanand Gautam

          Hi Muthu,

          For this you need to know how to extend a class. Create an Exception and extend that class with Throwable / Exception which ever suits you best. And inside that class do whatever you want to do with your exception. You can print custom message or perform any other operation.

          Now throw this exception from code where you are handling the login section.

          Hope it help.

          Regards
          Vivekanand Gautam

          Reply
  2. zufri

    Hi,

    From what i understand, ArithmeticException is an unchecked exception not checked. It still can compile. Example for checked exception are SQLException, IOException.

    Reply
  3. vivek

    Your tutorial is very good for beginners and thanks for sharing it.

    While in “Exceptions” section, I think the tutorial is truncated and also images do not appear. Can you please fix it?

    Thanks you!!

    Reply
    1. Vivekanand Gautam

      Hi Vivek,

      Thanks for your comment. Probably image has been deleted by me(My mistake). I will create a new article on Exception covering all the aspect and will upload the same soon.

      Meanwhile thank you for letting me know about this problem.

      Regards

      Reply
  4. dev nayak

    I am not getting the complete of any topic like exception,thread etc.
    There is no next botton or previous.so how can I get the complete
    Detail of a topic.

    Reply

Leave A Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.