Exception Handling

What is an exception?

  • An Exception is an unwanted event that interrupts the normal flow of the program.
  • When an exception occurs program execution gets terminated. In such cases, we get a system generated error message. The good thing about exceptions is that they can be handled in Java. By handling the exceptions we can provide a meaningful message to the user about the issue rather than a system generated message, which may not be understandable to a user.

Why an exception occurs?

  • Opening a non-existing file in your program.
  • Network connection problem.
  • Invalid input data provided by user.
  • Accessing array index out of range.

Advantage of Exception Handling

  • Ensures that the flow of the program doesn’t break when an exception occurs.

Examples

  • NullPointerException
  • ArithmeticException
  • ArrayIndexOutOfBoundsException

Types of exceptions

  1. Checked exceptions
  2. Unchecked exceptions
  3. Error
exception-hierarchy
Hierarchy of Java Exception Classes

Checked exceptions

  • All exceptions other than Runtime Exceptions are known as checked exceptions.
  • Compiler checks them during compilation to see whether the programmer has handled them or not.
  • If these exceptions are not handled/declared in the program, you will get compilation error.

Examples of Checked Exceptions

  1. SQLException
  2. IOException
  3. ClassNotFoundException

Unchecked exceptions

  • Runtime Exceptions are also known as Unchecked Exceptions.
  • These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions

Examples of Unchecked Exceptions

  1. ArithmeticException
  2. NullPointerException
  3. ArrayIndexOutOfBoundsException

Error

  • Error is irrecoverable and which is out of programmer’s control.

Examples of Error

  1. OutOfMemoryError
  2. VirtualMachineError
  3. AssertionError
Keyword Description
try The “try” keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can’t use try block alone.
catch The “catch” block is used to handle the exception. It must be preceded by try block which means we can’t use catch block alone. It can be followed by finally block later.
finally The “finally” block is used to execute the important code of the program. It is executed whether an exception is handled or not.
throw The “throw” keyword is used to throw an exception.
throws The “throws” keyword is used to declare exceptions. It doesn’t throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.

Example

public class ExceptionExample {
	public static void main(String args[]) {
		try {
			int data = 100 / 0; // code that may raise exception
		} catch (ArithmeticException e) {
			System.out.println(e);
		}
		System.out.println("rest of the code...");
	}
}

Output

java.lang.ArithmeticException: / by zero
rest of the code...

Common Scenarios of Java Exceptions

int a = 50 / 0; // ArithmeticException

String s = null;
System.out.println(s.length()); // NullPointerException

s = "abc";
int i = Integer.parseInt(s); // NumberFormatException

int array[] = new int[5];
array[10] = 50; // ArrayIndexOutOfBoundsException

try

  • Java try block is used to enclose the code that might throw an exception. It must be used within the method.
  • If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.
  • Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

try {
	// code that may throw an exception
} catch (Exception e) {
	// Exception handling logic
}

Syntax of try-finally block

try {
	// code that may throw an exception
} finally {
	// this block will execute irrespective of exception
}

catch

  • Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception.
  • The catch block must be used after the try block only. You can use multiple catch block with a single try block.
  • If an exception occurs in the try block, the rest of the block code will not execute.
  • we can handle the exception using the parent class exception.

Multi-catch block

  • A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler.
  • At a time only one exception occurs and at a time only one catch block is executed.
  • All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.

Example on Multi-catch block

public class ExceptionExample {
	public static void main(String[] args) {
		try {
			int a[] = new int[5];
			a[5] = 30 / 0;
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		} catch (Exception e) {
			System.out.println("Parent Exception occurs");
		}
		System.out.println("rest of the code");
	}
}

What would be the output?

	public static void main(String[] args) {
		try {
			String s = null;
			System.out.println(s.length());
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		} catch (Exception e) {
			System.out.println("Parent Exception occurs");
		}
	}

What would be the output?

public static void main(String args[]) {
	try {
		int a[] = new int[5];
		a[5] = 30 / 0;
	} catch (Exception e) {
		System.out.println("common task completed");
	} catch (ArithmeticException e) {
		System.out.println("task1 is completed");
	} catch (ArrayIndexOutOfBoundsException e) {
		System.out.println("task 2 completed");
	}
}

finally

  • Java finally block is a block that is used to execute important code such as closing connection, stream etc.
  • Java finally block is always executed whether exception is handled or not.
  • Java finally block follows try or catch block.

What would be the output?

public static void main(String args[]) {
	try {
		int data = 25 / 5;
		System.out.println(data);
	} catch (NullPointerException e) {
		System.out.println(e);
	} finally {
		System.out.println("finally block is always executed");
	}
	System.out.println("rest of the code...");
}

What would be the output?

public static void main(String args[]) {
	try {
		int data = 25 / 0;
		System.out.println(data);
	} catch (NullPointerException e) {
		System.out.println(e);
	} finally {
		System.out.println("finally block is always executed");
	}
	System.out.println("rest of the code...");
}

What would be the output?

public static void main(String args[]) {
	try {
		int data = 25 / 0;
		System.out.println(data);
	} catch (ArithmeticException e) {
		System.out.println(e);
	} finally {
		System.out.println("finally block is always executed");
	}
	System.out.println("rest of the code...");
}

NOTE

  1. For each try block there can be zero or more catch blocks, but only one finally block.
  2. The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

Advantages of Spring Boot

Advantages of Spring Boot:

  1. Automatic configuration—Spring Boot can automatically provide configuration
    for application functionality common to many Spring applications
  2. Starter dependencies—You tell Spring Boot what kind of functionality you need,
    and it will ensure that the libraries needed are added to the build.
  3. The command-line interface—This optional feature of Spring Boot lets you write
    complete applications with just application code, but no need for a traditional
    project build.
  4. The Actuator—Gives you insight into what’s going on inside of a running Spring
    Boot application. Actuator offers the ability to inspect the internals of your application at runtime. With the Actuator installed, you can inspect the inner workings of your application, including details such as
    What beans have been configured in the Spring application context
    What decisions were made by Spring Boot’s auto-configuration
    What environment variables, system properties, configuration properties, and
    command-line arguments are available to your application
    The current state of the threads in and supporting your application
    A trace of recent HTTP requests handled by your application
    Various metrics pertaining to memory usage, garbage collection, web requests,
    and data source usage

How to print the results to console in a tabular format using java?

In this post, we will see how we can print the results in a table format to the standard output like the image as shown below.
Tabular OutputTo print the results like a table structure we can use either printf() or format() method.
Both the methods belong to the class java.io.PrintStream.

More

How to loop / iterate a List in 8 different ways using java

In this post, we will see 8 different ways to iterate/ loop a list of objects in java
In java a list object can be iterated in following ways:

  1. Using For Loop
  2. Using For Each Loop
  3. Using Iterator
  4. Using For Each Loop with Iterator
  5. Using ListIterator
  6. Using Enumeration
  7. Using While Loop
  8. Using do While Loop

To explain the iteration process, let’s use a custom domain object called ‘Country.java’, which has few properties like code, name, and currency. And we will add some country objects to the list for iteration.

Country.java

 public class Country {
	private String code;
	private String name;
	private String currency;

	public Country() {
		super();
	}
	public Country(String code, String name, String currency) {
		this.code = code;
		this.name = name;
		this.currency = currency;
	}
	@Override
	public String toString() {
		return code + "\t" + name + "\t"	+ currency;
	}

}
So let’s get started into various ways of iteration one by one.

#1 Using For Loop

  • A for loop is useful when you know how many times a task is to be repeated.
  • The elements of the list are accessed by the index position.
// #1 Using For Loop
for(int i = 0; i< countrySize; i++){
	System.out.println(countries.get(i));
}

#2 Using For Each Loop

  • NOTE: for each loop was introduced in JDK 1.5
  • The basic for loop was extended in Java 5 to make iteration over arrays and other collections more convenient. This newer for statement is called the enhanced for or for-each.
for(Country country: countries){
	System.out.println(country);
}

#3 Using Iterator

  • Iterator is interface and found in java.util package.
  • It is an improvement over Enumeration interface. Iterator takes the place of Enumeration since jdk 1.2
  • We can iterate only in one direction.
  • Iteration can be done only once. If you reach the end of series its done. If we need to iterate again we should get a new Iterator.
Iterator<Country> iterator1 = countries.iterator();
while(iterator1.hasNext()){
	System.out.println(iterator1.next());
}

#4 Using For Each Loop with Iterator
We can use Iterator in combination with for each loop to loop the list as shown below.

for(Iterator<Country> iterator2 = countries.iterator(); iterator2.hasNext();) {
	Country country = (Country) iterator2.next();
	System.out.println(country);
}

#5 Using ListIterator

  • Using ListIterator, we can iterate all elements of a list in either direction, modify the list during iteration, and obtain the iterator’s current position in the list.
  • You can access next element by calling next() method, and also you can access previous element by calling previous() method on the list.
ListIterator<Country> listIterator = countries.listIterator();
while(listIterator.hasNext()){
	System.out.println(listIterator.next());
}

#6 Using Enumeration

  • The Enumeration interface defines the methods by which you can enumerate the elements in a collection of objects.
  • This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code.
  • It has only two methods, hasMoreElements() and nextElement().
Enumeration<Country> enumeration = Collections.enumeration(countries);
while(enumeration.hasMoreElements()){
	System.out.println(enumeration.nextElement());
}

#7 Using While Loop

int count = 0;
while(count < countrySize){
	System.out.println(countries.get(count));
	count++;
}

#8 Using do While Loop

int i = 0;
do{
	 System.out.println(countries.get(i));
	 i++;
}while (i < countrySize);

IterateList.java

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class IterateList {
    private static String SEPARATOR_LINE = "----------------------";

    public static void main(String[] args) {
        List<Country> countries = new ArrayList<Country>();
        countries.add(new Country("IN", "India", "INR"));
        countries.add(new Country("CN", "China", "CNY"));
        countries.add(new Country("JP", "Japan", "JPY"));
        countries.add(new Country("FR", "France", "EUR"));
        int countrySize = countries.size();

        // #1 Using For Loop
        System.out.println("#1 Using For Loop"+"\n"+SEPARATOR_LINE);
        for(int i = 0; i< countrySize; i++){
            System.out.println(countries.get(i));
        }

        // #2 Using For Each Loop
        System.out.println("\n#2 Using For Each Loop"+"\n"+SEPARATOR_LINE);
        for(Country country: countries){
            System.out.println(country);
        }

        // #3 Using Iterator
        System.out.println("\n#3 Using Iterator"+"\n"+SEPARATOR_LINE);
        Iterator<Country> iterator1 = countries.iterator();
        while(iterator1.hasNext()){
            System.out.println(iterator1.next());
        }

        // #4 Using For Each Loop with Iterator
        System.out.println("\n#4 Using For Each Loop with Iterator"+"\n"+SEPARATOR_LINE);
        for(Iterator<Country> iterator2 = countries.iterator(); iterator2.hasNext();) {
            Country country = (Country) iterator2.next();
        	System.out.println(country);
        }

        // #5 Using ListIterator
        System.out.println("\n#5 Using ListIterator"+"\n"+SEPARATOR_LINE);
        ListIterator<Country> listIterator = countries.listIterator();
        while(listIterator.hasNext()){
            System.out.println(listIterator.next());
        }

        // #6 Using Enumeration
        System.out.println("\n#6 Using Enumeration"+"\n"+SEPARATOR_LINE);
        Enumeration<Country> enumeration = Collections.enumeration(countries);
        while(enumeration.hasMoreElements()){
        	System.out.println(enumeration.nextElement());
        }

        // #7 Using While Loop
        System.out.println("\n#7 Using While Loop"+"\n"+SEPARATOR_LINE);
        int count = 0;
        while(count < countrySize){
            System.out.println(countries.get(count));
            count++;
        }

        // #8 Using do While Loop
        System.out.println("\n#8 Using do While Loop"+"\n"+SEPARATOR_LINE);
        int i = 0;
        do{
         System.out.println(countries.get(i));
         i++;
        }
        while (i < countrySize);
    }
}

Iteration Output
toString() method of Country.java class is overridden so as to print the results in a more readable format.
WaysIterationList
Ponits to Remember

  1. Use do while loop only when there is at least 1 element in the list, otherwise you will encounter java.lang.IndexOutOfBoundsException exception.
  2. Iterator and ListIterator both are the interfaces of java.util package.
  3. Enhanced for loop is the most effective and simplest way to iterate the list.
  4. Iterator provides only 3 methods [hasNext(), next() and remove()]. But ListIterator(Subinterfaces of Iterator) provides some additional methods like add(), hasPrevious(), nextIndex(), previous(), previousIndex(), set(E e).