Friday, 26 February 2016

Exception Handling in Java

Exceptional handling is one of the best useful features provided by Java.
Exception can be any error that may occur during the execution of the program.
Example: When user tries to withdraw amount more than his account balance, an error occurs.
In Such situations instead of ending the program abnormally, Exception handling is used to throw the valid error messages to the end user.
The reasons for an exception can be mainly categorized into three categories:
1.       User(client) error
2.       Developer error
3.       Hardware error.
Exceptions are mainly divided into three categories
1.       Checked Exceptions
2.       Un checked Exceptions
3.       Error
Below is the hierarchy of exceptions. Throwable is the root class for all exceptions.

Checked Exceptions:  
v  Checked Exceptions are the exceptions which are checked by compiler. I.e. our program will not compile if do not handle these checked Exceptions.
v  All checked Exceptions are inherited from Exception class
v  Checked exceptions can be handled either by using try-catch block. Or by using throws keyword
v  Checked Exceptions are also called as Compile time Exceptions
Example:
In the below example user is trying to read a file called ‘chckedException.txt’ in D drive. There is a chance giving wrong location for the file.

File file=new File ("D: // chckedException.txt”);
 FileReader fr = new FileReader (file);

To handle such situations, java throws a compile time exception called FileNotFoundException which should be handled by the developer while developing the code.
Developer can use either try catch block or can choose to skip the exception handling by just throwing it using throws keyword.

Solution 1:
public void readFile()
{
Try
{
File file=new File ("D: // chckedException.txt”);
 FileReader fr = new FileReader (file);
}
Catch(FileNotFoundException ex)
{
System.out.println(“File does not exist at the given location”);
}
}
Solution 2
public void readFile() throws Exception
{
File file=new File ("D: // chckedException.txt”);
 FileReader fr = new FileReader (file);

}



Search This Blog