An exclusion (or special occasion) is an issue that appears throughout the performance of an application. When an Exception happens the ordinary movement of this system is interrupted and the software/Program ends abnormally, which isn’t advocated, so these exclusions must be managed.

An exclusion may happen for a variety of motives, under provided are some situations where exclusion happens.

A person has entered invalid information.

A document which should be exposed can not be located.

A network link was dropped at the center of communications or the JVM has run from storage.

Several of those exclusions are due to user error, the others by developer error, and the others by bodily assets that have failed for some reason.

According to these we now have three types of Exclusions you must know them to understand how different handling functions in Java,

Assessed exclusions: A checked exception is an exception occurring at the compile-time, these can also be referred to as as compile-time exclusions. These exclusions can not only be blown off during collection, the Computer Software Developer should just take care of (manage) these exclusions.

By way of example, if you utilize FileReader type in your application to examine information from a record, if the document specified in its constructor does not exist, then an FileNotFoundException happens, and compiler encourages the developer to manage the exception.

Transfer java.io. File;
import java.io. FileReader;

Community group FilenotFound_Demo

Community fixed void main(Chain args[])
Record document=new Record(“E://file.txt”);
FileReader fr = new FileReader(file);
If you attempt to gather the above software you’re getting exclusions as shown below.

C:>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; should be caught or declared to be thrown
FileReader fr = new FileReader(record);
^
1 malfunction

Notice: Since the methods examine() and shut() of FileReader group tosses IOException, it is possible to find that compiler informs to manage IOException, in addition to FileNotFoundException.

Unrestrained exclusions: An Uncontrolled exception is an exception occurring during the time of delivery, these will also be known as as Run Time Exclusions, these contain development pests, like reasoning problems or poor use of an API. Run time exceptions are blown off during system.

By way of example, if you’ve announced an variety of dimensions 5 in your application, and attempting to c all the 6th element of the assortment then an ArrayIndexOutOfBoundsExceptionexception happens.

Community group Unchecked_Demonstration

Community fixed void main(Chain args[])
int num[]=1,2,3,4;
System.out.println(num[5]);
If you gather and run the above software you’ll get exclusion as shown below.

Exception in line “main” java.lang. ArrayIndexOutOfBoundsException: 5
at Exclusions.Unchecked_Demonstration.chief(Unchecked_Demonstration.java:8)

Malfunctions: These aren’t exceptions in any way, but issues that appear beyond the handle of an individual or the developer. Malfunctions are usually blown off in your signal because it is possible to seldom do such a thing about a mistake. By way of example, in case a stack over-flow occurs, a mistake may appear. Not only that , they are blown off during system.

Exclusion Structure:

All exception types are sub-types of the java.lang. Exclusion type. The exception type is a sub-class of the Throwable course. Apart from the exclusion type there’s still another sub-class called Malfunction that will be produced from your Throwable course.

Malfunctions are unusual conditions that occur in situation of serious failures, these aren’t managed by the java software. Malfunctions are created to signal errors created by the run-time atmosphere. Instance : JVM has gone out of Memory. Typically applications can not cure errors.

The Exception group h-AS two main sub-classes: IOException group and RuntimeException Course.

Exceptions Methods:

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

SN Methods 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.

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. 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
}

The code which is prone to exceptions is placed in the try block, when an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block.

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, 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 2 elements. Then the code tries to access the 3rd 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 the 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. 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 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.

Example:

Here is code segment showing 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;
}

Catching multiple type of exceptions

Since Java 7 you can handle more than one exceptions using a single catch block, this feature simplifies the code. Below given is the syntax of writing

catch (IOException|FileNotFoundException ex) {
   logger.log(ex);
   throw ex;

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature.

You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.

Try to understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly.

The following method declares that it throws a RemoteException:

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, 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:

import java.io.*;
public class className
{
   public void withdraw(double amount) throws RemoteException,
                              InsufficientFundsException
   {
       // Method implementation
   }
   //Remainder of class definition
}

The finally block

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.

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.

A finally block appears 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.
}

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{
         a[0] = 6;
         System.out.println("First element value: " +a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

This would produce the following result:

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

Note the following:

  • A catch clause cannot exist without a try statement.
  • It is not compulsory to have finally clauses when ever a try/catch block is present.
  • The try block cannot be present without either catch clause or finally clause.
  • Any code cannot be present in between the try, catch, finally blocks.

The try-with-resources

Generally when we use any resources like streams, connections etc.. we have to close them explicitly using finally block. In the program given below we are reading data from a file using FileReader and we are closing it using finally block.

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadData_Demo {

   public static void main(String args[]){
      FileReader fr=null;		
      try{
         File file=new File("file.txt");
         fr = new FileReader(file);  char [] a = new char[50];
         fr.read(a); // reads the content to the array
         for(char c : a)
         System.out.print(c); //prints the characters one by one
      }catch(IOException e){
          e.printStackTrace();
       }
       finally{	
          try{
              fr.close();
          }catch(IOException ex){		
               ex.printStackTrace();
           }
       }
    }

}

try-with-resources, also referred as automatic resource management. is a new exception handling mechanism that was introduced in Java7, which automatically closes the resources used within the try catch block.

To use this statement you simply need to declare the required resources within the parenthesis, the created resource will be closed automatically at the end of the block, below given is the syntax of try-with-resources statement.

try(FileReader fr=new FileReader("file path"))
   {
   //use the resource
   }catch(){
      //body of catch 
    }
   }

Below given is the program that reads the data in a file using try-with-resources statement.

import java.io.FileReader;
import java.io.IOException;

public class Try_withDemo {

   public static void main(String args[]){
      		
      try(FileReader fr=new FileReader("E://file.txt")){
         char [] a = new char[50];
         fr.read(a); // reads the contentto the array
         for(char c : a)
         System.out.print(c); //prints the characters one by one
      }catch(IOException e){
          e.printStackTrace();
       }   
   }
}

Following points are to be kept in mind while working with try-with resources statement.

  • To use a class with try-with-resources statement it should implement AutoCloseable interface and the close() method of it gets invoked automatically at runtime.
  • You can declare more than one class in try-with-resources statement.
  • while you declare multiple classes in the try block of try-with-resources statement these classes are closed in reverse order.
  • Except the deceleration of resources within the parenthesis every thing is same as normal try/catch block of a try block.
  • The resource declared in try gets instantiated just before the start of the try-block.
  • The resource declared at the try block is implicitly declared as final.

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 predefined Exception class to create your own Exception. 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.

Example:

// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception
{
   private double amount;
   public InsufficientFundsException(double amount)
   {
      this.amount = amount;
   } 
   public double getAmount()
   {
      return amount;
   }
}

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

// File Name CheckingAccount.java
import java.io.*;

public class CheckingAccount
{
   private double balance;
   private int 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);
      }
   }
   
   public double getBalance()
   {
      return balance;
   }
   
   public int getNumber()
   {
      return number;
   }
}

The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.

// File Name BankDemo.java
public class BankDemo
{
   public static void main(String [] args)
   {
      CheckingAccount c = new CheckingAccount(101);
      System.out.println("Depositing $500...");
      c.deposit(500.00);
      
      try
      {
         System.out.println("\nWithdrawing $100...");
         c.withdraw(100.00);
         System.out.println("\nWithdrawing $600...");
         c.withdraw(600.00);
      }catch(InsufficientFundsException e)
      {
         System.out.println("Sorry, but you are short $" + e.getAmount());
         e.printStackTrace();
      }
    }
}

Compile all the above three files and run BankDemo, this would produce the following result:

Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
        at CheckingAccount.withdraw(CheckingAccount.java:25)
        at BankDemo.main(BankDemo.java:13)

Common Exceptions:

In Java, it is possible to define two catergories of Exceptions and Errors.

  • JVM Exceptions: – These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException,
  • Programmatic exceptions: – These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalStateException.

 

Leave a Reply

Your email address will not be published. Required fields are marked *