Thursday, June 13, 2013

Exceptions in Java

Hi All,
Welcome to Java-recent.
In this post I will discuss about concepts related to Exceptions in Java.
Agenda
  • What is an Exception?
  • Exception hierarchy
  • Types of Exceptions
  • Exception handling
  • Throwing an Exception
  • Creating custom exceptions etc.

Exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program -----Reference from http://docs.oracle.com
Generally exceptions are thrown due to
  • Programming errors like null pointer exception
  • A particular resource requested cannot be found like a file not found
  • Network unavailability or JVM out of memory etc.
Let’s see a simple example for better understanding
Example:- In this example we are trying to write to a file it throws IO Exception
This exception is handled in catch block
public class ExceptionExample {
public static void main(String[] args) {
try {
BufferedWriter bw=new BufferedWriter(new FileWriter("c:\\Javarecent.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
Exception hierarchy:-

Take the diagram from slides and modify it


The blocks in red color will be unchecked exceptions which we will  discuss later in detail.
The one in blue block(IOException etc) are checked exceptions,which will be checked during compile time

Types of Exceptions:- There are three types of exceptions
  1. Checked
  2. Unchecked
  3. Error
Differences between types of exceptions is classic java interview question
Checked exceptions:-
  • These exceptions extends Exception class
  • These are checked during compile time
    • When we write the code for fetching a file, during compile time JVM tells us to handle the exception like java.io.IOException etc.
  • A good programming should effectively handle this kind of exceptions and continue program execution
Example:-
public class ExceptionExample {
public static void main(String[] args) {
try {
FileWriter fw=new FileWriter("c:\\Javarecent.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
Explanation :- When we write FileWriter statement compiler will force to catch/throw the exception. Here we are catching the Exception

Unchecked exceptions:-
  • These exceptions extends Exception class
  • They occur during run time, compiler will not be able to figure out them
  • A bad programming will cause this type of exceptions
    • Suppose we have a String instance variable and it is not assigned, but we will call substring () method on this ,during compile time the compiler will not be able to find, when we actually run the program exception will be thrown-so they are termed as runtime/checked exceptions
    Example code :-
      public class ExceptionExample {
    private String empName;
    public static void main(String[] args) {
    ExceptionExample ee=new ExceptionExample();
    System.out.println(ee.empName.length());
    }
    }
Will the above code will work fine? Compile time will not tell developer to catch the exception,only during run time of the program we will throw an exception likejava.lang.NullPointerException
These kind of runtime exceptions occurs due to bad programming .

Error :-
  • These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from 
  • Error cannot be handled by JVM, so the program execution halts
  • Most of the errors occur due to hardware/network/memory issues
    • Suppose we have a web application which needs to connect to database, if the database server is down. Then application will throw exception though we handle them they will not be useful program execution
    • Suppose if there is outOfMemory error then the application halts, its irrecoverable so termed as error
  • Error occurs due to external elements

    Exception handling in Java :-
We have seen different types of exceptions now let’s see how to handle them.
Java provides different mechanisms to handle Exceptions
  1.  Using catch block
  2. Using throws key word
try-catch-finally are the three blocks required for Exception handling.
The code that might cause exceptions is written try block; they are handled in catch block.
Finally has a special importance which we will discuss later.
Syntax:-
try
{
}catch(Exceptions……….)
{
}finally
{
}
There should not be any code between try-catch-finally blocks, they should be continuous.
1.Using catch block:-
If we want to handle the exceptions in the method it occurred then we use catch block.
  • There can be multiple catch blocks for a single try
  • Nested try-catch-finally blocks can be present
  • Catch block takes an Exception object as a parameter
Example :-
public class ExceptionExample {
public static void main(String[] args) {
try {
BufferedWriter bw=new BufferedWriter(new FileWriter("c:\\Javarecent.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
}

}
Declaring multiple catch blocks
  • Suppose our application throws java.io.FileNotFoundException
    So if we  define catch block as
    catch(Exception e)
    {
    }
     This will catch all the exceptions. Handling exceptions this way is bad programming practice. We should specify the most possible/low level exception and then move to higher levels accordingly
    So the correct way of handling is
    catch(java.io.FileNotFoundException fnfe)
    {
    }
    catch(Exception e)
    {
    }

Now we will see the other way of handling the exceptions.
2.Using throws key word:-
If we do not want to handle the exception where it occur we want to propagate it to calling methods,
Then we need to use throws key word this will throw the possible exceptions to calling methods, there we need to catch them or that method can further throw them.


public class ExceptionExample {
public void writeFile() 
{ try {
BufferedWriter bw=new BufferedWriter(new FileWriter("c:\\Javarecent.txt"));
}
finally {
} }
public static void main(String[] args) throws IOException {
ExceptionExample ee=new ExceptionExample();
try {
ee.writeFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

In the above example as we are not catching the exception in writefile() example,we are throwing it using throws key word.
In main method we are calling the writefile() method,so main method should catch the Exception or it should thrown the exception,in that case it will be thrown to JVM.

Stack trace information:-
Definition: A stack trace provides information on the execution history of the current thread and lists the names of the classes and methods that were called at the point when the exception occurred. A stack trace is a useful debugging tool that you'll normally take advantage of when an exception has been thrown. Reference from http://docs.oracle.com


Advantages of catching Exceptions:-
  1. Used for smooth execution of a program
  2. Easy to know the exception and log them to an external file for analysis
  3. Grouping and differentiating error types
Interview questions:-
  1. What is an Exception?
  2. Difference between error and Exception?
  3. Difference between checked and unchecked exceptions?
  4. Better ways of handling Exceptions

Key take away points:-
  1. Throwable is the super class for all errors/exceptions
  2. Checked exceptions are checked during compile time
  3. Unchecked/Runtime exceptions occur due to bad programming
  4. Always put catch(Exception e) as a last catch block
  5. Errors are irrecoverable

    In my next article i will post on how to write custom exceptions....

                      Happy Learning

    Please provide your valuable comments on this article and share it across your network.


No comments:

Post a Comment

Like and Share