Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Tuesday, 9 April 2013

Difference between Checked and Unchecked Exceptions - Exception Handling in Java - Part 1/3

Today we will discuss a very powerful feature of Java i.e. ‘Exception Handling’. In this particular blog we will see; ‘What is Exception?’, ‘Types of Exception?’ and ‘How to handle Exceptions in Java?’. Before we start lets first discuss something about Exceptions and Error and their hierarchy in Java.

What is an Exception?

An Exception is an unwanted situation or event that occurs during the execution of a program, exceptions may lead to termination of the program if not handled properly.

Exceptions in Java?

Whenever an error occurs within a Java code on runtime, an Object is created called Exception Object, it contains all information about exception including type or class of exception and the location where the exception is occurred in the program.

Java run time environment searches for an appropriate handler for this exception object, it starts searching from the current method to calling methods in reverse and at last the main method. If an appropriate handler code is found then the exception is handled normally, otherwise program terminates.

Event handling is a mechanism that provides handler code snippets to the program, so that the exceptions can be caught and programming flow can be maintained.


Exception Hierarchy in Java

Throwable is the parent class of all Exceptions that is further extended by two classes, Exception and Error. In Java Exceptions can be categorized in two main streams


1) Unchecked Exception
2) Checked Exception

1) Unchecked Exception

The exceptions that are not checked at compile time are called unchecked exceptions, classes that extends RuntimeException comes under unchecked exceptions. Examples of some unchecked exceptions are listed below.

ArithmeticException

Mathematical operations that are not permitted in normal conditions i.e. dividing a number from ‘0’.
package com.beingjavaguys.core;

public class ExceptionTest {

public static void main(String[] args) {
int i = 10/0;
}
}
   

Console :

Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.beingjavaguys.core.ExceptionTest.main(ExceptionTest.java:6)

ArrayIndexOutOfBoundsException

Trying to access an index that does not exists or inserting values to wrong indexes results to ArrayIndesOutOfBound Exception at runtime.
package com.beingjavaguys.core
public class ExceptionTest {

public static void main(String[] args) {
int arr[] = {'0','1','2'};
System.out.println(arr[4]);
}
}
   

Console :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at com.beingjavaguys.core.ExceptionTest.main(ExceptionTest.java:7)

NullPointerException

Trying to access a null object or performing operations on an object having a null value.
package com.beingjavaguys.core;
import java.util.ArrayList;

public class ExceptionTest {

public static void main(String[] args) {
String string = null;
System.out.println(string.length());
}
}
   

Console

Exception in thread "main" java.lang.NullPointerException
at com.beingjavaguys.core.ExceptionTest.main(ExceptionTest.java:9)

Some common Unchecked Exceptions in Java

Here is a list of some common Unchecked Exceptions in Java language. ArithmeticException
ArrayStoreException
BufferOverflowException
BufferUnderflowException
CannotRedoException
CannotUndoException
ClassCastException
CMMException
ConcurrentModificationException
DOMException
EmptyStackException
IllegalArgumentException
IllegalMonitorStateException
IllegalPathStateException
IllegalStateException
ImagingOpException
IndexOutOfBoundsException
MissingResourceException
NegativeArraySizeException
NoSuchElementException
NullPointerException
ProfileDataException
ProviderException
RasterFormatException
SecurityException
SystemException
UndeclaredThrowableException
UnmodifiableSetException
UnsupportedOperationException


2) CheckedExceptions

Exceptions that are checked at compile-time are called checked exceptions, in Exception hierarchy all classes that extends Exception class except UncheckedException comes under checked exception category.

In certain situations Java Compiler forced the programmer to write a Exception handler at compile time, the Exceptions thrown in such situation are called Checked Exception, see the example below
try {
    String input = reader.readLine();
    System.out.println("You typed : "+input); // Exception prone area
    } catch (IOException e) {
      e.printStackTrace();
}
   
While writing a code to read or write something from files or even from or to console, an checked Exception i.e. IOException is thrown, these exceptions are checked at compile time and we are forced to write a handler at compile time. That’s why we called these exceptions Checked Exceptions. We will know about try-catch and other Exception Handling stuff in next blog.

Some common CheckedExceptions in Java

Here is a list of some common Unchecked Exceptions in Java language. IOException
FileNotFoundException
ParseException
ClassNotFoundException
CloneNotSupportedException
InstantiationException
InterruptedException
NoSuchMethodException
NoSuchFieldException

We will cover this part in Next Tutorial in details.

In this particular blog we came across the basics of Exception Handling and What is difference between Checked and Unchecked Exceptions in Java language, in next blog we will cover exception handling strategies using try, catch and finally. To learn try-catch and finally examples go to Next Blog in the series from Here.










Thanks for reading !
Being Java Guys Team

9 comments:

  1. thank u sir its very use full...

    ReplyDelete
  2. Simple but excellent explanations!!!

    ReplyDelete
  3. Hi, Being Java Guys Team

    Thanks for the post.

    I found a mistake in this post, update

    Some common CheckedExceptions in Java
    Here is a list of some common Unchecked Exceptions in Java language. IOException

    to

    Here is a list of some common Checked Exceptions in Java language. IOException

    ReplyDelete
  4. Thanks,good information

    ReplyDelete

Search Tutorials
Like Us on Facebook

Like Us On Google+