Exceptions in java

In java, An Exception is an event which causes a break in the normal flow of an application. An exception is an object which is thrown when a program is executing.

An exception can occur for many different reasons, including the following:

  • Entering the data beyond the range of an array.
  • An attempt to divide a number by zero.
  • An attempt to read a file which does not exists.
  • 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.

To understand how exception handling works in Java, we need to 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 example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.

Unchecked exceptions:

An unchecked exception is an exception that occurs that probably could have been avoided by the programmer.

For example, if a user tries to insert 6th element in an array where the size of the array was 5 only, an exception occurs. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.

Errors:

These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in our code because we can rarely do anything about an error.

For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Java provides exception handling blocks and a bunch of classes present in java.lang package for handling the exceptions and making our program to function smoothly.

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. The following figure describes the hierarchy of the Exceptions classes. exceptios-architecture-java In Java, exceptions are objects. When we throw an exception, we throw an object. We can't throw just any object as an exception, however only those objects whose classes descend from Throwable.

Throwable serves as the base class for an entire family of classes, declared in java.lang, that our program can instantiate and throw.

The objects which are thrown in as exceptions holds the information about the exceptions such as type, error message line on which the exception has been raised etc.

As we can see Throwable has two direct subclasses, Exception and Error. Exceptions (members of the Exception family) are thrown to signal abnormal conditions that can often be handled by some catcher, though it's possible they may not be caught and therefore could result in a dead thread.

Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError, that may not be so easy to handle.

In general, code we write should throw only exceptions, not errors. Errors are usually thrown by the methods of the Java API, or by the Java virtual machine itself.

Different types of Exception’s objects are thrown when according to the situation for example JVM throws a FileNotFoundException class’s object when an application tries to open a file which doesn’t exist.

Therefore java has provided a rich set of classes to track and handle such exceptions.

list of unchecked of exceptions

ArithmeticException

Arithmetic error, such as divide-by-zero.

ArrayIndexOutOfBoundsException

Array index is out-of-bounds

ArrayStoreException

Assignment to an array element of an incompatible type.

ClassCastException

Invalid cast.

IllegalArgumentException

Illegal argument used to invoke a method.

IllegalMonitorStateException

Illegal monitor operation, such as waiting on an unlocked thread.

IllegalStateException

Environment or application is in incorrect state.

IllegalThreadStateException

Requested operation not compatible with current thread state.

IndexOutOfBoundsException

Some type of index is out-of-bounds.

NegativeArraySizeException

Array created with a negative size.

NullPointerException

Invalid use of a null reference.

NumberFormatException

Invalid conversion of a string to a numeric format.

SecurityException

Attempt to violate security.

StringIndexOutOfBounds

Attempt to index outside the bounds of a string.

UnsupportedOperationException

An unsupported operation was encountered.

List of checked packages

Here is a list of Checked Exception classes in java.lang package

.

Exception

Description

ClassNotFoundException

Class not found.

CloneNotSupportedException

Attempt to clone an object that does not implement the Cloneable interface.

IllegalAccessException

Access to a class is denied.

InstantiationException

Attempt to create an object of an abstract class or interface.

InterruptedException

One thread has been interrupted by another thread.

NoSuchFieldException

A requested field does not exist

NoSuchMethodException

A requested method does not exist.

Handling Exceptions using try, catch and finally

Java provides some exception handlers component block and keywords to handle the exception thrown by the java program.

The blocks include try, catch and finally besides these blocks java provides two keywords throw and throws which help in creating user-defined exceptions. Let us know about each one by one.

The try block :

Most important part of exception handling in the program is to identify statements which may cause an exception.

Statements which uses an arithmetic operation, arrays manipulation, input output operations or communicating to network and so on are the candidate to throw exceptions. The first step to construct an exception handler is to identify such statements and put them inside a try {…} block.


Syntax: 
Try
{  
	//statement(s);
 } catch and finally blocks 

The try block may contain one or more valid statements which may throw an exception. The try block is followed by at least one catch or finally block.

Whenever any line of code within the try block throws an exception control moves to the appropriate handler to handle the exception and rest of the lines of the try block are not executed.

If no exception is thrown within the try block all the statements are executed. Therefore, in any case program execution does not terminate abnormally.


// Without try… catch
public class DivideTest {
 public static void main(String… ar) {
  int a, b, c;
  a = 20;
  b = 5;
  c = a / b;
  System.out.println(c);
  b = 0;
  c = a / b; // throws an exception and stops execution   
  System.out.println(c);
  System.out.println("Bye!!");
 }
}

With try…catch


// With try…catch
public class DivideTest {
 public static void main(String… ar) {
  int a, b, c;
  try {
   a = 20;
   b = 5;
   c = a / b;
   System.out.println(c);
   b = 0;
   c = a / b; //throws an exception and moves the control to catch.           
   System.out.println(c);
  } catch (Exception ex) {
   System.out.println("can’ t divide by 0");
  } //execution continues.                                 
  System.out.println("Bye!!");
 }
}

A try block must be followed by at least one catch or finally block. However there can be more than one catch block for a single try block.

There should not be any intermediate statement between try and catch blocks. A program can have any number or try and catch blocks. They can be nested also.

The catch block

A try block is followed by one or more catch block which acts as a handler for the exception thrown. Each catch block is an exception handler and handles the type of exception indicated by its argument.

The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name.

A catch block contains the alternative code which needs to be executed if and when an exception is thrown. Regardless of the number of catch blocks defined only one catch block is executed at a time which is based on the type of exception thrown in the try block.


//Syntax: 								
try {
 //code
} catch (ExceptionType1 ex) {
 //code
} catch (ExceptionType2 ex) {
 //code
}

//Example:


//Example: 
public class ExceptionExample {
 public static void main(String argv[]) {
  int num1 = 10;
  int num2 = 0;
  int result = 0;
  int arr[] = new int[5];
  try {
   //maximum index number of arr is 4 as value of i becomes 5 exception is thrown.     
   for (int i = 0; i <= 5; i++)
    arr[i] = i + 1;
   result = num1 / num2; //num2 is 0 and throws an arithmetic exception.        System.out.println("Result of Division : " + result); 
  } catch (ArrayIndexOutOfBoundsException e) {
   //invoked when an array index goes beyond the limit.         
   System.out.println("Err: Array Out of Bound");
  } catch (ArithmeticException e) {
   //invoked when an arithmetic exception occurs such as divide by zero         
   System.out.println("Err: Divided by Zero");
  } catch (Exception e) {
   //able to handle any type of exception    
   System.out.println(e.getMessage());
  }
 }
}

Output: Err: Array Out of Bound

In the above example try block may throw two exception ArrayIndexOutOfBoundsException and ArithmeticException.

As soon as the any one of the exception occurs control is transferred to the appropriate catch block containing the type of exception is thrown and the corresponding code within the catch block is executed.

If we are not sure which type of exception may occur, a catch with the type Exception can be written.

It can handle any kind of exception as the Exception class is super class of all the Exceptions. Such can catch block must be placed after every catch block.

Putting such catch block immediately after the try block followed by catch block with specific type of exception would be meaningless. As they would never be executed since that is able to handle any type of exception.

The finally block

The finally block is an optional block provided in exception handling which is executed whether an exception occurs or not.

A try catch segment may be followed by a finally block containing code which must be executed regardless of exception being thrown. Codes such as closing a database connection, releasing a resource, closing a file after all the manipulations have been performed can be put inside the finally block.

The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup.


//Syntax: 
try {
 //code 
} catch (ExceptionType1 ex) {
 //code 
} catch (ExceptionType2 ex) {
 //code
}.
finally {
 //code
}

Example for try..catch..finally


//Example: 
public class ExceptionExample {
 public static void main(String argv[]) {
  int num1 = 10;
  int num2 = 0;
  int result = 0;
  int arr[] = new int[5];
  try {
   //maximum index number of arr is 4 as value of i becomes 5 exception is thrown.     
   for (int i = 0; i <= 5; i++)
    arr[i] = i + 1;
   result = num1 / num2; //num2 is 0 and throws an arithmetic exception        
   System.out.println("Result of Division : " + result);
  } catch (ArrayIndexOutOfBoundsException e) {
   //invoked when an array index goes beyond the limit.         
   System.out.println("Err: Array Out of Bound");
  } catch (ArithmeticException e) {
   //invoked when an arithmetic exception occurs such as divide by zero         System.out.println("Err: Divided by Zero");       
  } catch (Exception e) {
   //able to handle any type of exception    
   System.out.println(e.getMessage());
  } finally {
   System.out.println("Statement within
    finally are always executed"?);
  }
 }
}

Output: Err: Array Out of Bound

Statement within finally are always executed

Methods in Exceptions

Two of common methods of Exception class which is either overridden from Throwable class.

public String getMessage() : Returns the detail string message of this exception.

public void printStackTrace() : Prints this throwable and its backtrace to the standard error stream.

Creating user-defined Exceptions

Consider a scenario where you have been assigned a task of finding a specific book, and then reading and explaining its contents to a class of students.

The required sequence may look like:

  • Get the specified book
  • Read aloud its contents
  • Explain the contents to a class of students.

But what happens if you can't find the specified book? You can't proceed with the rest of the action without it so you need to report back to the person who assigned the task to you.

This unexpected event (missing book) prevents you from completing your task. By reporting it back, you want the originator of this request to take corrective or alternate steps.

In such a scenario, the originator of the request must know the situation when the method of a class may throw an exception.

Before we learn to create user-defined exception we must understand the functionality of throws and throw keywords in java.

The throws keyword

The throws keyword is used in method signature to declare Exception possibly thrown by any method. If a method does not handle a checked exception, the method must declare it using the throws keyword.

The throws keyword with the specific types of exceptions (separated by commas) in the method’s signature are used to tell the caller method that the called method may cause the specified exceptions. Therefore the caller method must provide the handlers for those exceptions. The throws keyword can be used in a java program in two circumstances

  • One when a designer of the method of a class wants to warn the programmer that using this method may cause an exception. Any exception which is following the throws statement becomes the checked exception. Means providing a handler is a must, if we do not provide handlers for such exception compiler gives an error.
  • Another when a programmer is calling a method which throws an exception, the caller method can also be declared as throwing the same exception. (it can be an alternative of try…catch but not robust).

//Syntax: 

<modifier > <return type > methodname(list of parameters) throws ExceptionType1, ExceptionType2, … {
  //method body
 }

The throw keyword :

The throw keyword is used to explicitly throw an exception from inside a method. The throw statement requires a single argument: a throwable object.

Throwable objects are instances of any subclass of the Throwable class. As we have already discussed, the Java platform provides numerous exception classes.

All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program.

We handle the exception using try…catch block , before we handle the exceptions they must have been thrown from somewhere. The throw keyword is used in every situation whenever an exception is thrown.

Whether it is ArithmeticException or FileNotFoundException.


//Syntax: 
<modifier > & ltreturn type > methodname(list of parameters) throws ExceptionType1, ExceptionType2, … {
 //method body 
 throw new ExceptionType(); // where ExceptionType can be any subclass of throwable. 
}

Besides the Exception classes defined in java.lang package a programmer can also create their own exception as the need of the application.

Now the question is, why we create a user-defined exception, when java already provides a rich set of exception classes.

There are situations in the program when a particular type of exception cannot be represented using the existing exception classes.

For creating our own exception class, we must create a class which extends the Exception class. The new class will be considered as a checked exception.

An exception class is just like other classes which may contain useful fields and methods.

Appending the word Exception after the name of the class is a good programming practice to create a user-defined exception class. It makes the exception class to be identified easily. Now let us consider a situation where we want to create an exception class InvalidAgeException and throw this exception when the age of an employee is either below 18 or greater than 60.


//Defining Exception class  
public class InvalidAgeException extends Exception {
 //instance variables  
 private String message;
 private int age;
 //constructor definition
 public InvalidAgeException(String messg, int age) {
  this.messg = messg;
  this.age = age;
 }

 //method to return error message  
 public String getMessage() {
  return messg + ": "+age;
 }
}



//Class which throw InvalidAgeException

public class Employee {
 private String name;
 private int age;
 public String getName() {
  return this.name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  Return this.age;
 }
 public void setAge(int age) {
  //condition to throw an exception of type InvalidAgeException.   
  If(age & lt18 && age > 60)
  throw new InvalidAgeException(“Invalid age passed", age);
  else
   this.age = age;
 }
}



//class which make use of the Employee class and handle the exception thrown. 

public class MainClass {
 public static void main(String… ar) {
  Employee e = new Employee();
  Try {
   e.setName(“John");
   e.setAge(17);
  } catch (InvalidAgeException ex) {
   System.out.println(ex.getMessage());
  } finally {
   System.out.println(“Employee Details");
   System.out.println(“Name: "+e.getName());
   System.out.println(“Age: "+e.getAge());
  }
 }
}
//-----Output:

Invalid age passed Employee Details
Name: John
Age: 0

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Protractor Online Training : We have closed registration for training

Please do email to chercher.tech@gmail.com for any queries

If you already registered then please do check your email for the Webex link for the training starting from 15th Nov 2018
 
Join My Facebook Group
Join Group