An exception is what that causes to distract the flow of execution, of a program.An exception can occur because of:
A user has entered invalid data.
A file that opened but cannot be found.
The network connection gone down or lost in the middle of communications, or the JVM has run out of memory.
To understand how exception handling works in Java, you should understand the three categories of exceptions:
Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For ex:-, if a file that should be opened, but the file is not found, an exception occurs. These type of exceptions can't be ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. But, runtime exceptions are ignored at the time of compliation.
Errors: These are not exceptions, but problems that arise beyond the control of the user or the programmer. But also, Errors are typically ignored in your code because you can rarely do anything about an error. For ex:- if a stack overflow occurs, an error will arise. These are also ignored at the time of compilation.
Exception Hierarchy:
All exception classes are subclass of the java.lang.Exception class. The exception class is a subclass of the Throwable class. More over, other than the exception class there is another subclass called Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These type of conditions normally happen in case of severe failures, which are not handled or controlled by the java programs. The Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Genrally programs cannot recover from errors.
The Exception class has two main subclasses : IOException class and RuntimeException Class.
So, here is a list of most common checked and unchecked Java's Built-in Exceptions.
Exceptions Methods:
There is the list of important medthods available in the Throwable class below.
SN
Methods with Description
1
public String getMessage()
Returns a detailed message about the exception that has occurred. And this message is initialized in the Throwable constructor.
2
public Throwable getCause()
This method returns the cause of the exception as represented by a Throwable object.
3
public String toString()
This method returns the name of the class concatenated with the result of getMessage()
4
public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, an error output stream.
5
public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. An element at index 0 represents the top of the call stack & the last element in the array represents the method at the bottom of the call stack.
6
public Throwable fillInStackTrace()
This method fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. The try block/catch block is placed around the code that might generate an exception. The Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
A catch statement involves declaring the type of exception you are trying to catch.And If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. Also ,If the type of exception that occurred is listed in a catch block, then the exception is passed to the catch block much as an argument is passed into a method parameter.
Example:
The following is an array is declared with two elements. Then the code tries to access the third element of the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest{
public static void main(String args[])
{
try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
This would produce following result:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Multiple catch Blocks:
A try block can be followed by multiple catch blocks. And the syntax for multiple catch blocks looks like the following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
The above statements describes three catch blocks, but its up to you, that you can have any number of them after a single try.
So, if an exception occurs in the protected code, then the exception is thrown to the first catch block in the list and If the data type of the exception thrown matches ExceptionType1, it must caught there.But If not, the exception passes down to the second catch statement. This will continues until the exception either is caught or falls through all catches, and in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.
Example:
Here is code that shows how to use multiple try/catch statements.
try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}
catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}
The throws/throw Keywords:
If a method does not handle a checked exception, then the method must declare it using the throwskeyword.
This throws keyword appears at the end of a method's signature.
You can throw an exception, by using the throw keyword. So try to understand the different in throws and throw keywords.
This method declares that it throws a RemoteException below:
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare that it throws more than one exception,and in which case the exceptions are declared in a list separated by commas. For ex:- the following method declares that it throws a RemoteException and an InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
The finally Keyword
A finally block always executes, whether there is an exception or not.
Finally block enables you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
A finally block is used at the end of the catch blocks and has the following syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}







No comments:
Post a Comment