Part 20: Exceptions in Java with real time Example.

JAVA | 29 comments

Java Exceptions

An exception or exceptional event is a problem. This is getting up during the execution of a program. When an Exception happens the normal flow of the program is disrupted and the program  terminates unusually. This is not recommended, consequently, these exceptions are to be handled.An exception can occur for many different reasons. where an exception occurs?

  • A user has entered an 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.
  • Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.
  • Based on these, we have three categories of Exceptions. You need to understand them to know how exception handling works in Java.

Checked exceptions:

A checked exception is checked or notified by the compiler at compilation-time. These are also called as compile time exceptions. These exceptions cannot simply be ignored. The programmer should take care of (handle) these exceptions. For instance, if 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.

Example:

import java.io.File;

import java.io.FileReader;

public class Example {

   public static void main(String args[]) {               

      File file = new File("C://file.txt");

      FileReader fr = new FileReader(file);

   }

}

Output

C:\>javac Example.java

Example.java:8: error: unreported exception Example; must be caught or declared to be thrown

FileReader fr = new FileReader(file);                      ^

1 error

Note: Since the methods read() and close() of FileReader class throws IOException, detect the compiler informs to handle IOException, along with FileNotFoundException.

Unchecked exceptions:

An unchecked exception is an exception occurs at the time of execution. These are also called as Runtime Exceptions comprise programming bugs example as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. For sample, if declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

Example

public class Example

{  

   public static void main(String args[]) {

      int number[] = {1, 2, 3, 4};

      System.out.println(number[5]);

   }

}

Output

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5

at Example.main(Unchecked_Demo.java:8)

Errors:

These are not exceptions at all though problems that stand up beyond the control of the user or the programmer. Errors are typically ignored in code because programmer can rarely do anything about an error. For case, if a stack overflow occurs, an error will ascend. They are also ignored at the time of compilation.

Exception Hierarchy

All kind of 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 irregular conditions that happen in case of severe failures, these 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.

The Exception class has two main subclasses: IOException class and RuntimeException Class. A list of most common checked and unchecked Java’s Built-in Exceptions. Exceptions Methods:

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

  • getMessage(): Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
  • Throwable getCause():Returns the cause of the exception as represented by a Throwable object.
  • toString():Returns the name of the class concatenated with the result of getMessage().
  • printStackTrace():Prints the result of toString() along with the stack trace to System.err, the error output stream.
  • 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.
  • 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:

Syntax

try {

// Protected code

} catch (ExceptionName e1) {

// Catch block

}

The code which is likely to 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

// File Name : ExcepTest.java

import java.io.*;

public class ExcepExample

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

   }

}

Output

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:

Syntax

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, though  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 exception using a single catch block, this feature simplifies the code.

catch (IOException|FileNotFoundException example) {

logger.log(example);

throw example;

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. To throw an exception, either a newly instantiated one or an exception that just caught, by using the throw keyword. There is some key 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 :

Example

import java.io.*;

public class classExample {

   public void deposit(double amount) throws RemoteException {

      // Method implementation

      throw new RemoteException();

   }

   // Rest 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 illustration, the following method declares that it throws a RemoteException and an InsufficientFundsException:

Example

import java.io.*;

public class classExample {

   public void withdraw(double amount) throws RemoteException,

      InsufficientFundsException {

      // Method implementation

   }

   // Rest 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.By means of 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 classExample{

   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 will produce the following result −

Output

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3

First element value: 6

The finally statement is executed

Note : A catch clause cannot exist without a try statement.

  • It is not obligatory to have finally clauses whenever 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.

try-with-resources

To use any resources alike streams, connections, etc. need  to close them explicitly using finally block. In the following program, reading data from a file using FileReader and closing it using finally block.

Example

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

public class ReadDataExample {

   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 mentioned as automatic resource management, is a new exception handling mechanism was introduced in Java 7. It is an automatically closes the resources used within the try catch block. To use this statement need to declare the required resources within the parenthesis, and the created resource will be closed automatically at the end of the block. Following is the syntax of Try with resources statement.

Syntax

try(FileReader fr = new FileReader("file path")) {

   // use the resource

   } catch () {

      // body of catch

   }

}

Following is the program that reads the data in a file using Try with resources statement.

Example

import java.io.FileReader;

import java.io.IOException;

public class TryExample {

   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. In order to use a class with try statement it should implement AutoCloseable interface and the close() method of it gets invoked automatically at runtime.It allows or can declare more than one class in try-with-resources statement.

While declare multiple classes in the try block of try with resources statement these classes are closed in reverse order. Except the declaration of resources within the parenthesis everything is the 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

To create your own exceptions in Java. All exceptions must be a child of Throwable. To write a checked exception that is automatically enforced by the Handle or Declare Rule, need to extend the Exception class. If want to write a runtime exception, need to extend the RuntimeException class.

define own Exception class as below :

class MyException extends Exception {

}

In order 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 ExceptionExample.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 own user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.

// File Name CheckAccount.java

import java.io.*;
public class CheckAccount {

   private double balance;

   private int number;
   public CheckAccount (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 CheckAccount.

// File Name BankDemo.java

public class BankExample {

   public static void main(String [] args) {

      CheckingAccount cA = new CheckingAccount(101);

      System.out.println("Depositing $500...");

      cA.deposit(500.00);

      try {

         System.out.println("\n Withdrawing $100...");

         c.withdraw(100.00);

         System.out.println("\n Withdrawing $600...");

         c.withdraw(600.00);

      } catch (InsufficientFundsException e) {

         System.out.println(" Sorry !, but you are short $" + e.getAmount());

         e.printStackTrace();

      }

   }

}


Output

Depositing $500…

Withdrawing $100…

Withdrawing $600…

Sorry!, but you are short $200.0

InsufficientFundsException

at CheckingAccount.withdraw(CheckAccount.java:25)

at BankExample.main(BankDemo.java:13)

Common Exceptions: In Java, it is possible to define two catergories of Exceptions and Errors. Apart them, JVM Exceptions are exceptions/errors exclusively or logically thrown by the JVM. For Instances: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException. Another exceptions namely programmatic Exceptions. These exceptions are thrown explicitly by the application or the API programmers. Examples: IllegalArgumentException, IllegalStateException.

Chapter 6: Software Testing with example Process

What is Testing? Testing is the process of evaluating a system or its component(s) with the intent to find whether it satisfies the specified requirements or not. In simple words, testing is executing a system in order to identify any gaps, errors, or missing...

Chapter – 4: Project management with Example Procedures.

Project management Software project management is an essential part of software engineering. Projects need to be managed because professional software engineering is always subject to organizational budget and schedule constraints. The project manager‘s job is to...

You may find interest following article

Chapter 6: Software Testing with example Process

What is Testing? Testing is the process of evaluating a system or its component(s) with the intent to find whether it satisfies the specified requirements or not. In simple words, testing is executing a system in order to identify any gaps, errors, or missing requirements in contrary to the actual requirements. According to ANSI/IEEE 1059 standard, Testing can be...

Chapter-5: Cost Estimation Tutorial in Software Engineering

Cost Estimation Tutorial Cost is s strategic concept in software development for the following reasons: Project management: Estimating cost is extremely crucial in carrying out project management activities such as scheduling, planning and control.Feasibility Study: Making investment decisions regarding software projects requires full cost breakdown and analysis...

Chapter – 4: Project management with Example Procedures.

Project management Software project management is an essential part of software engineering. Projects need to be managed because professional software engineering is always subject to organizational budget and schedule constraints. The project manager‘s job is to ensure that the software project meets and overcomes these constraints as well as delivering...

Chapter -3: Agile Software Development Method Process

Agile Software Development Although there are many approaches to rapid software development, they share some fundamental characteristics: The processes of specification, design, and implementation are interleaved. There is no detailed system specification, and design documentation is minimized or generated automatically by the programming environment used to...

Chapter 2: Software processes with various model

Objectives: understand the concepts of software processes and software process models;have been introduced to three generic software process models and when they might be used;know about the fundamental process activities of software requirements engineering, software development, testing, and evolution;understand why processes should be organized to cope with...

Frequency Word for IELTS Listening

Frequency Word for IELTS Listening School a. Library  WordSentence1. Shelf 2. Librarian 3. The stacks 4. Return 5. Fine 6. Magazine 7. Copier  8. Overdue  9. Reading room  10. Reference room  11. Periodical room  12. Study lounge  13. Catalogue  14....

Chapter 8: Gantt chart Project Development in SDLC

Gantt chart Project DevelopmentSchedule (project management) The project scheduleis the tool that communicates what work needs to be performed, which resources of the organization will perform the work and the timeframes in which that work needs to be performed. The project scheduleshould reflect all of the work associated with delivering the project on time....

Chapter 7: Feasibility Analysis in Software Develoment Life Cycle.

Feasibility AnalysisWhat is Feasibility Analysis?? An analysisand evaluation of a proposed project to determine if it (1) is technically feasible, (2) is feasible within the estimated cost, and (3) will be profitable for Organization. Feasibility analysis guides the organization in determining whether to proceed with the project. Feasibility analysis also identifies...

Chapter 6: Data Flow Diagram in Software Development Life Cycle.

Data Flow Diagram What is DFD? A data flow diagram (DFD) is a graphical representation of the "flow" of data through an information system, modelling its process aspects.A DFD is often used as a preliminary step to create an overview of the system, which can later be elaborated.Show users how data moves between different processes in a system. Figure 1: DFD Symbols...

Chapter 5: System request on SDLC

System Request In most organizations, project initiation begins by preparing a  system request. A  system request is a document that describes the business reasons for building a system and the value that the system is expected to provide.The project sponsor usually completes this form as part of a formal system project selection process within the...

Chapter 4: SDLC design Phase

SDLC design Phase DFD (Design Analysis)Architectural DesignUI DesignDatabase DesignProgram DesignArchitectural design (logical)Network designClient –server designClient designServer designCloud ComputingDatabase designER diagramRelational diagramDDL (not now..!!)Program design (physical)Investigating the hardware/software platformPhysical DFDData storageData...

Chapter 3: SDLC and its Life cycle Phases.

What is SDLC? The systems development life cycle (SDLC), also referred to as the application development life-cycle, is a term used in systems engineering, information systems and software engineering to describe a process for planning, creating, testing, and deploying an information system. Career Paths for System Developers Systems Development Life Cycle Building...

Chapter 2: SDLC Key Features For SYSTEMS ANALYST.

Once upon a time, software development consisted of a programmer writing code to solve a problem or automate a procedure. Nowadays, systems are so big and complex that teams of architects, analysts, programmers, testers and users must work together to create the millions of lines of custom-written code that drive our enterprises.To manage this, a number of system...

Chapter 1: System analysis and Design Overview.

System analysis, a method of studying a system by examining its component parts and their interactions. •It provides a framework in which judgments of the experts in different fields can be combined to determine what must be done, and what is the best way to accomplish it in light of current and future needs.  •The system analyst (usually a software engineer or...

Chapter 4: Concept Of Sampling, Quantization And Resolutions

Concept Of Sampling, Quantization And Resolutions Conversion of analog signal to digital signal: The output of most of the image sensors is an analog signal, and we can not apply digital processing on it because we can not store it. We can not store it because it requires infinite memory to store a signal that can have infinite values. So we have to convert an...

Chapter 3: Images and Conversions in Digital Image Process

Images And Conversions There are many type of images, and we will look in detail about different types of images, and the color distribution in them. The binary image The binary image as it name states, contain only two pixel values. 0 and 1. In our previous tutorial of bits per pixel, we have explained this in detail about the representation of pixel values to...

Chapter 2: Concept of Pixel in Digital Image Process

Concept of Pixel Pixel Pixel is the smallest element of an image. Each pixel correspond to any one value. In an 8-bit gray scale image, the value of the pixel between 0 and 255. The value of a pixel at any point correspond to the intensity of the light photons striking at that point. Each pixel store a value proportional to the light intensity at that particular...

Part 6: IELTS Academic Writing Task 1 For Diagram/Graph Vocabulary

Vocabulary to show the sequence: You must write a summary of at least 150 words in response to a specific graph (bar, line, or pie graph), table, chart, or procedure in Writing Task 1 of the IELTS Academic test (how something works, how something is done). This job assesses your ability to choose and report the most important aspects, describe and compare data,...

Part 5: IELTS Academic Writing Task 1 Formal and Informal expressions.

Formal and Informal expressions and words: You must write a summary of at least 150 words in response to a specific graph (bar, line, or pie graph), table, chart, or procedure on the IELTS Academic test (how something works, how something is done). Few more informal expressions with their formal versions are given below. Since IELTS is a formal test, your writing...