1. Introduction :
It is an unexpected unwanted event that disturbs the entire flow of the program.
RealTimeExample:
1) SleepingException
2) TirePuncharedException
If we are not handling exceptions, the program may terminate abnormally without releasing allocated resources. This is not a graceful termination. Being a good programming practice compulsory we should handle exceptions for graceful termination of the program.
Exception handling means it is not repairing an exception we are providing alternative ways to continue the program normally. For example, if our programming requirement is to read the data from the London file if at runtime the London file is not available, we have to provide a local file as part of exception handling. So that respect of the program will be continued normally
2. Exception and error:
An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be handled.
An exception can occur for many different reasons, below given are some scenarios where exception occurs.
• A user has entered invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run out of memory. An error occurs at compile time. It is not more dangerous than the exception.
3. Exception class Hierarchy:


4. Types of Exceptions:

5. Inbuilt Methods:
SN. |
Method with Description |
1. |
public
String getMessage() Returns a
detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor. |
2. |
public
Throwable getCause() Returns the
cause of the exception as represented by a Throwable object. |
3. |
public
String toString() 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, the error
output stream. |
5. |
public
StackTraceElement [] getStackTrace() Returns an
array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array
represents the method at the bottom of the call stack. |
6. |
public
Throwable fillInStackTrace() Fills the
stack trace of this Throwable object with the current stack trace, adding to
any previous information in the stack trace. |
6. Exception handling mechanism:
6.1 Try block:
The code that you want to monitor for the exceptions writes that code into the try block. 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(ExceptionType e1) {
//Exception handling code
}
6.2 Catch block:
A try block is followed by a catch block which handles the exceptions. It contains the exception handling code.
Syntax:
catch(ExceptionType e1)
{
//Exception handling code
}
If an exception occurs in a try block, the exception object is created and that is thrown to the matching catch block. The catch block will handle the exception.
Here either we can print the exception object or can call the printStackTrace method and display the information of the exception that has occurred.
Exception object contains the following information: type of exception, class of exception.
But if we call method printStackTrace() from catch block then it will contain the following information: at which line it occurred, in which method it occurred, who is the caller of that method, from which line that method gets called, in which class it occurred, in which file it occurred, and so on.....
Example:
The following is an array that is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.
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("Code after catch block"); } }
|
Output:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Code after catch block
try with Multiple catch Blocks:
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:
try { // Protected code } catch (ExceptionType1 e1) { // Child ExceptionType // Handling code } catch (ExceptionType2 e2) { // Child ExceptionType // Handling code } catch (ExceptionType3 e3) { // Parent Exception Type // Handling code } |
The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list.
If the data type of the exception thrown matches ExceptionType1, it gets caught there.
If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. If there is no matching catch, an exception will be handled by the default exception handler.
try { file = new FileInputStream(fileName); x = (byte) file.read(); } catch (FileNotFoundException f) { f.printStackTrace(); return -1; } catch (IOException i) { i.printStackTrace(); return -1; } |
The following code will generate compile time error
try { file = new FileInputStream(fileName); x = (byte) file.read(); } catch (Exception e) { e.printStackTrace(); return -1; } catch (IOException i) // Not valid! { i.printStackTrace(); return -1; } catch (FileNotFoundException f) // Not valid! { f.printStackTrace(); return -1; } |
Note: We can not write the catch taking superclass reference variable of exception hierarchy before that of the subclass.
Compiler Error will be: exception already caught. Thus While writing try with multiple catches, catch with subclass should be before catching with superclass.
6.3 throw clause :
When we want to explicitly throw an exception then we use the throw clause. We can throw an exception, either using a new instance or using an exception object by using the throw keyword.
throw new TypeOfException(parameters);
This method can explicitly throw an exception using the throw keyword.
6.4 throws clause: '
If a method is not able to handle a particular exception, the method must declare it using the throws keyword with its definition. It will throw that exception out of itself. Then the caller has the responsibility to handle that exception. The throws keyword appears at the end of a method's signature. A method can throw multiple exceptions using the throws clause.
Syntax:
throws Type1Exception,Type2Exception
Try to understand the difference between throws and throw keywords. The following method shows the use of both throw and throws
public class className { public void deposit(double amount) throws RemoteException { // Method implementation if(remoteObject==null) throw new RemoteException(“null remote object”); } //Remainder of class definition }
|
A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException:
Difference between throw and throws
throw |
throws |
To manually throw the exception |
To throw the
exception out of the method towards caller when the callee method is not able
to handle that exception |
Example: public void show() { throw new
NullPointerException(); } public void show() { throw new
NullPointerException(“pointing to null reference”); } |
Example: public void show()
throws IOException, NumberFormatException { // body of
the method } |
It is followed by an instance of the class |
It is
followed by name of the class |
It is declared within the method body |
It is
declared with the method definition |
It can throw only one exception at a time |
It can
declare multiple exception classes at a time |
The exception that is thrown by throw can be handled within that method |
The exception
declared in throws can not be handled by that same method that's why it is
propagated towards the caller. |
6.5 The finally block :
The finally keyword is used to create a block of code that follows a try block or try-catch block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. For e.g. u can write the file closing or database closing code in the finally block if the file is opened in a try block or database connections are opened in the try block.
finally{ // important code, cleanuptype statements } A finally
block which appears at the end of the catch blocks and has the following syntax: try { // Protected code }catch(ExceptionType1 e1) { // handling code }catch( ExceptionType2
e2) { // handling code }catch( ExceptionType3
e3) { // handling code }finally { // cleanuptype statements } |
Example:
public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" + a[3]); } catch
(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } finally { System.out.println("The finally statement is executed"); } } }
|
public class CheckingAccount {
private double balance; private int number; public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public CheckingAccount(int number) { this.number = number; }
public void deposit(double amount) { balance += amount; }
public void withdraw(double amount) throws InsufficientFundsException { if (amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } }
class InsufficientFundsException extends Exception { double needs;
InsufficientFundsException(double needs) { this.needs = needs; }
@Override public String toString() { return "InsufficientFundsException [needs=" + needs + "]"; } }
|
import java.util.Scanner; public class UserDefinedException { public static void main(String[] args) { Scanner
sc = new Scanner(System.in); CheckingAccount
ca = new CheckingAccount(4070856); try { ca.setBalance(50000); System.out.println("The initial balance is: " + ca.getBalance()); System.out.println("Enter the amount to deposit: "); double damount = sc.nextDouble(); ca.deposit(damount); System.out.println("The balance is: " + ca.getBalance()); System.out.println("Enter the amount to withdraw: "); double wamount = sc.nextDouble(); ca.withdraw(wamount); }
catch
(InsufficientFundsException e) { System.out.println("Balance is insufficient"); e.printStackTrace(); }
catch (Exception e) { e.printStackTrace(); } System.out.println("The code after catch continued...."); } } |
Output :
The initial balance is: 50000.0 Enter the amount to deposit: 2000 The balance is: 52000.0 Enter the amount to withdraw: 53000 Balance is insufficient InsufficientFundsException [needs=1000.0] The code after catch continued.... at
com.renuka.jan.blog.CheckingAccount.withdraw(CheckingAccount.java:37) at com.renuka.jan.blog.UserDefinedException.main(UserDefinedException.java:17) |
Thus InsufficientFundsException get generated when a user enters the amount to withdraw which is more than the available balance and it is get handled at the caller side
ConversionConversion EmoticonEmoticon