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
- Checked
- Unchecked
- 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 elementsException 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
- Using catch block
- 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
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:-
- Used for smooth execution of a program
- Easy to know the exception and log them to an external file for analysis
- Grouping and differentiating error types
Interview
questions:-
- What is an Exception?
- Difference between error and Exception?
- Difference between checked and unchecked exceptions?
- Better ways of handling Exceptions
- Importance of finally block[http://java-recent.blogspot.in/2013/06/importance-of-finally-block-in-java.html]
Key
take away points:-
- Throwable is the super class for all errors/exceptions
- Checked exceptions are checked during compile time
- Unchecked/Runtime exceptions occur due to bad programming
- Always put catch(Exception e) as a last catch block
- Errors are irrecoverableIn my next article i will post on how to write custom exceptions....Happy LearningPlease provide your valuable comments on this article and share it across your network.
Contact me @ sudheer@javarecent.com or admin@java-recent.com
No comments:
Post a Comment