Exception Handling in Java

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: 

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are not normally trapped from the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. 

Example: JVM is out of Memory. Normally programs cannot recover from errors.

Note: The Error is a class in the Exception hierarchy. 

It is not related to a compile-time error. The Exception class has a subclass: RuntimeException Class.

4. Types of Exceptions: 

1. Checked exceptions: 
A checked exception is an exception that occurs at the compile time, these are also called compile-time exceptions. These exceptions cannot simply be ignored at the time of compilation, the Programmer should take care of (handle) these exceptions. For example, if you use FileReader class in your program to read data from a file if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception. 

Since the methods read() and close() of FileReader class throws IOException, you can observe that compiler notifies to handle IOException, along with FileNotFoundException. 

2. Unchecked exceptions: 
An Unchecked exception is an exception that occurs at the time of execution but not checked at compile-time, these are also called Runtime Exceptions. Runtime exceptions are ignored at the time of compilation. For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs. 

5. Inbuilt Methods:

Following is the list of important methods available in the Throwable class.

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:

There are several keywords that are used in exception handling. These keywords can be used to create blocks and clauses. 

• try : block 
• catch : block 
• finally : block 
• throw : clause / statement 
• throws : clause / statement

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

}

Note: The try block must have atleast one catch block or finally block

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");

                    }

             }

}

Output: 

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 

The finally statement is executed 

Execution Sequence :

 1. try{}finally{}: first, try block will get executed, then if an exception occurs then, finally will get executed and later exceptions will be caught by the default exception handler. 

2. try{}catch{}finally{}: first try block will get executed, then if an exception occurs and if there is the matching catch, an exception will be handled in that catch, then finally will get executed.

7. User-Defined Exceptions: 

You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes: 

• All exceptions must be a child of Throwable. 

• If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. 

• If you want to write a runtime exception, you need to extend the RuntimeException class. We can define our own Exception class as below: 

class MyException extends Exception{ } 

You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException. 

 

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

8. Chained Exceptions: 

The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception. For example, imagine a situation in which a method throws an ArithmeticException because of an attempt to divide by zero. 

However, the actual cause of the problem was that an I/O error occurred, which caused the divisor to be set improperly

9. Exception Propagation: 

An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. 

This is called the exception propagation. It can be achieved via the throws clause.

 

Recommend Topics:










Previous
Next Post »

ConversionConversion EmoticonEmoticon

:)
:(
=(
^_^
:D
=D
=)D
|o|
@@,
;)
:-bd
:-d
:p
:ng