Category Archives: Java

Java : Shallow and Deep Object Cloning


Pr-requisite : Marker Interface in Java and Use, CloneNotSupportedException

In object oriented programming object copy or copy of object are possible many ways like copy constructor or copy of object. Here we will focus on both the ways for copy of object.

  • Shallow Copy or Shallow Cloning
  • Deep Copy or Deep Cloning

See also : Java : Shallow Cloning Vs Deep Cloning

Example of Shallow Cloning and Deep Cloning
Java : Shallow Cloning and Deep Cloning

Shallow Copy or Shallow Cloning

Whenever we use default implementation of copy of object means it create new instance of object and copies all the fields to the object new fields and if fields are non primitive or reference type variable to copy to new fields as reference of that non-primitive fields.

clone() method by default support shallow copy of object().  for implementing clone() method you have to implement Cloneable interface which is marker interface.

Shallow copy example by constructor

import java.util.Arrays;

public class Courses {
	String[] courseArr;
	// Shallow copy by constructor because in copy taking reference of object
	public Courses(String[] courseArr) {
		super();
		this.courseArr = courseArr;
	}
	@Override
	public String toString() {
		return "Courses [courseArr=" + Arrays.toString(courseArr) + "]";
	}

	public static void main(String[] str) {
	String[] courseArr = { "Math", "Physics", "Chemistry", "Hindi", "English" };
	Courses courses = new Courses(courseArr);
	System.out.println(courses);
	courseArr[2] = "Computer";//while changing in passed object will reflect on copy of object
	System.out.println(courses);
	}
}

Output


Courses [courseArr=[Math, Physics, Chemistry, Hindi, English]]
Courses [courseArr=[Math, Physics, Computer, Hindi, English]]

Shallow copy by clone method

In this example doing  shallow copy by clone method default way by implementing Cloneable interface and overriding clone() method which will by default make copy of object but here sub object course field in Student object will take reference of copied student object. It means if make any change on course object values will reflect same on copy object. clone method will always throw CloneNotSupportedException which always need to handle.

class Courses {
	String course1;
	String course2;
	String course3;

	public Courses(String course1, String course2, String course3) {
		this.course1 = course1;
		this.course2 = course2;
		this.course3 = course3;
	}
}

class Student implements Cloneable {
	int id;
	String name;
	Courses courses;

	public Student(int id, String name, Courses courses) {
		this.id = id;
		this.name = name;
		this.courses = courses;
	}

	// Default version of clone() method. It creates shallow copy of an object.
	// CloneNotSuportedException is checked exception always need to handle that
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}

public class ShallowCopyInJava {
	public static void main(String[] args) {
		Courses science = new Courses("Physics", "Chemistry", "Math");
		Student student1 = new Student(1020, "Saurabh", science);
		Student student2 = null;

		try {
			// Creating a clone of student1 and assigning it to student2
			student2 = (Student) student1.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}

		// Printing the subject3 of 'student1'
		System.out.println(student1.courses.course3); // Output : Maths

		// Changing the course3 of 'student2'
		student2.courses.course3 = "Biology";

		// This change will be reflected in original student 'student1'
		System.out.println(student1.courses.course3); // Output : Biology
	}
}

Output


Math
Biology

Note: If class is having only primitive type values or Immutable object there is no difference between Shallow and Deep Cloning of object.

Deep Copy or Deep Cloning

Whenever we need own copy not to use default implementation (shallow copy or shallow cloning) of object. Always implement according to our need and make sure all the member of  class also having deep copied of fields.

If using cloneable interface and overriding clone() method of object class make sure member objects /reference objects also having deep copy of fields.

Deep copy example by constructor

import java.util.Arrays;

public class Courses {
	String[] courseArr;

	// Deep copy object because copy actual fields value not references
	public Courses(String[] courseArr) {
		super();
		if (courseArr != null) {
			this.courseArr = new String[courseArr.length];
			for (int i = 0; i <courseArr.length; i++) {
				this.courseArr[i] = courseArr[i];
			}
		}
	}

	@Override
	public String toString() {
		return "Courses [courseArr=" + Arrays.toString(courseArr) + "]";
	}

	public static void main(String[] str) {
		String[] courseArr = { "Math", "Physics", "Chemistry", "Hindi", "English" };
		Courses courses = new Courses(courseArr);
		System.out.println(courses);
		courseArr[2] = "Computer";// while changing in passed object will reflect on copy of object
		System.out.println(courses);
	}
}

Output


Courses [courseArr=[Math, Physics, Chemistry, Hindi, English]]
Courses [courseArr=[Math, Physics, Chemistry, Hindi, English]]

Deep copy by clone method
In this example doing  deep copy by clone method but handle copying each individual reference object copy separately as in Student class clone() method. It means if make any change on course object values will not reflect same on copy object. clone method will always throw CloneNotSupportedException which always need to handle.

class Courses implements Cloneable{
String course1;
String course2;
String course3;

public Courses(String course1, String course2, String course3) {
this.course1 = course1;
this.course2 = course2;
this.course3 = course3;
}

protected Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}

class Student implements Cloneable
{
int id;
String name;
Courses courses;

public Student(int id, String name, Courses courses)
{
this.id = id;
this.name = name;
this.courses = courses;
}

//Overriding clone() method to create a deep copy of an object.
//CloneNotSuportedException is checked exception always need to handle that

protected Object clone() throws CloneNotSupportedException
{
Student student = (Student) super.clone();
student.courses = (Courses) courses.clone();
return student;
}
}

public class DeepCopyInJava
{
public static void main(String[] args)
{
Courses science = new Courses("Physics", "Chemistry", "Math");
Student student1 = new Student(1020, "Saurabh", science);
Student student2 = null;

try
{
//Creating a clone of student1 and assigning it to student2
student2 = (Student) student1.clone();
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}

//Printing the subject3 of 'student1'
System.out.println(student1.courses.course3); //Output : Math
//Changing the subject3 of 'student2'
student2.courses.course3 = "Biology";
//This change will not be reflected in original student 'student1'
System.out.println(student1.courses.course3); //Output : Math
}
}

Output


Math
Math

Conclusion

Here you learn about Shallow and Deep copy  of object by constructor and implementing by clone() method of Cloneable Interface which is marker interface.

Advertisements

Java : Shallow Cloning Vs Deep Cloning


Pre-requisite : 

Below are  the list of differences between shallow cloning and deep cloning in java.

Example of Shallow Cloning and Deep Cloning
Java : Shallow Cloning and Deep Cloning

Shallow Cloning

  • Cloned Object and original object are not 100% disjoint.
  • Any changes made to cloned object will be reflected in original object or vice versa.
  • Default version of clone method creates the shallow copy of an object.
  • Shallow copy is preferred if an object has only primitive fields.
  • Shallow copy is fast and also less expensive.

Example: Shallow Cloning Example

Deep Cloning

  • Cloned Object and original object are 100% disjoint.
  • Any changes made to cloned object will not be reflected in original object or vice versa.
  • To create the deep copy of an object, you have to override clone method.
  • Deep copy is preferred if an object has references to other objects as fields.
  • Deep copy is slow and very expensive.

Example: Deep Cloning Example

Java : Immutable Class/Collection Creation


What is Mutable/Immutable Class?

A class is called as immutable class once object is created , we can not change it’s fields/objects values. If values are changeable then it’s mutable class.

Designing Rule

Classes should be immutable unless there’s a very good reason to make them mutable….
If a class cannot be made immutable, limit its mutability as much as possible.

In java all the wrapper classes and String class is immutable. For Ex: immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc.

How to make a class Immutable Class?

Below are step by step guide to make a class Immutable:

Step 1 : Don’t provide “setter” methods that modify fields or objects referred to by fields.
Step 2 : Make all fields final and private.
Step 3 : Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
Step 4 : If the instance fields include references to mutable objects, don’t allow those objects to be changed: Don’t provide methods that modify the mutable objects.
Step 5 : Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor.
If necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

What are Benefits of Immutable Object?

  1. Immutable objects are thread-safe so you will not have any synchronization issues.
  2. Immutable objects are good Map keys and Set elements, since these typically do not change once created.
  3. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
  4. Immutability makes it easier to parallelize your program as there are no conflicts among objects.
  5. Immutable objects internal state of your program will be consistent even if you have exceptions.
  6. References to immutable objects can be cached as they are not going to change.

How to create Immutable Lists, Sets or Maps?

In JAVA 8 added “unmodifiable” method and JAVA 9 added “of” factory method to make collections like lists, sets and maps as immutable.  for example :

JAVA 8


Unmodifiable List
List stringList = Arrays.asList("Facing", "Issues", "On", "IT");
stringList = Collections.unmodifiableList(stringList);

Unmodifiable Set
Set stringSet = new HashSet<>(Arrays.asList("Facing", "Issues", "On", "IT"));
stringSet = Collections.unmodifiableSet(stringSet);

Unmodifiable Map
Map<String,Integer> stringMap = new HashMap<String, Integer>();
stringMap.put("Facing",1);
stringMap.put("Issues",2);
stringMap.put("On",3);
stringMap.put("IT",4);
stringMap = Collections.unmodifiableMap(stringMap);

JAVA 9


Unmodifiable List
List stringList = List.of("Facing", "Issues", "On", "IT");
Unmodifiable Set
Set stringSet = Set.of("Facing", "Issues", "On", "IT");

Unmodifiable Map
Map stringMap = Map.of("Facing",1, "Issues",2, "On",3, "IT",4);

 

Immutable Class Example


//make class final so that method not override
public final class ImmutableClass {
	final String pancardNumber;
	final String aadharNumber;
	final DOB dob;

	// Create object
	public ImmutableClass(String pancardNumber, String aadharNumber, DOB dob) {
		this.pancardNumber = pancardNumber;
		this.aadharNumber = aadharNumber;
		this.dob = dob;
	}
    //No setter method so that no fields get modifiable
	public String getPancardNumber() {
		return pancardNumber;
	}

	public String getAadharNumber() {
		return aadharNumber;
	}

	@Override
	public String toString() {
		return "ImmutableClass [pancardNumber=" + pancardNumber + ", aadharNumber=" + aadharNumber + ", dob=" + dob
				+ "]";
	}
}
public class  DOB {
	private int day;
	private int month;
	private int year;
	public DOB(int day, int month, int year)
	{
	this.day=day;
	this.month=month;
	this.year=year;
	}

	public int getDay() {
		return day;
	}

	public int getMonth() {
		return month;
	}

	public int getYear() {
		return year;
	}

	@Override
	public String toString() {
		return "DOB [day=" + day + ", month=" + month + ", year=" + year + "]";
	}

}
public class ImmuTableClassTest {

	public static void main(String[] args) {
		DOB dob = new DOB(24, 04, 1992);
		ImmutableClass immutableClass = new ImmutableClass("ABCD12345", "1234567890123456", dob);
		System.out.println(immutableClass);

	}

}

Output


ImmutableClass [pancardNumber=ABCD12345, aadharNumber=1234567890123456, dob=DOB [day=24, month=4, year=1992]]

Conclusion

In this blog you understand below points:

  • What is mutable and Immutable classes?
  • How make a class Immutable?
  • How to make collections like Lists, Sets and maps  immutable by Java 8 and Java 9?
  • Immutable class example.

References

https://docs.oracle.com/javase/9/core/creating-immutable-lists-sets-and-maps.htm

Multiple catch block (Java 7+) Rules


Pre-Requisite: Java: Exception Handling Tutorial

Java 7 improved multi catch to handle in single block so that reduce the number of lines of code. Here we will discuss about the rules  to handle multi catch block and difference while implementing multi catch with Java 7+.

Multi Catch Rules

Java Catch Exception Rules
5 Rules for Catching Exceptions in Java (7+)

Here you will know all above multiple catch block rules in details:

Rule 1 : One try block can associated with multiple catch blocks.

As per exception handling one try block safe guard can associated with multiple catch block to handle different type of exception depend on code statement on try block. Like below handling ArithmeticException and NumberFormatException in different catch blocks. You can see complete example in end of this blog.

try
{
//some code here
}
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}

Rule 2 : If the exceptions have parent-child relationship, the catch blocks must be sorted by the most specific exceptions first, then by the most general ones.

In this below example FileNotFoundException is sub class of IOException thats what most specific exception FileNotFoundException will always come before IOException.

try {
	File file = new File("ABC.txt");
	BufferedReader br = new BufferedReader(new FileReader(file));

	String st;
	while ((st = br.readLine()) != null)
		System.out.println(st);

	} catch (FileNotFoundException ex) {
		ex.printStackTrace();
	} catch (IOException ex) {
		ex.printStackTrace();
	}

Rule 3 : If the exceptions are not in the same inheritance tree, i.e. they don’t have parent-child relationship, the catch blocks can be sorted any order.

As exception handling blocks ArithmeticException and NumberFormatException i are not having any relation like parent and child , so order sequence of these two exceptions doesn’t matter. Like in rule 1 we use as order ArithmeticException and NumberFormatException while in this rule using order as  NumberFormatException  and ArithmeticException.

try
{
//some code here
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}

Rule 4 : If we catch the most general exception first, then we also catch other exceptions which are sub-types of the general exception.

If we are using generic Exception or RuntimeException to handle all type of exception this catch block should always be in last. otherwise compiler will throw exception as  “Unreachable catch block for ArithmeticException

Wrong way

multi catch error for generic exception

Right Way

try
{
//some code here
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
catch (Exception ex)
{
//To handle all othertype exception exception NumberFormatException<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
System.out.println("Exception" + ex);
}

Rule 5 : In java 7 multiple exceptions can be handle throw single block when need to print or throw some generic exception.

Since Java 7,  we can combine multiple  exceptions in single catch clause by pipe (|) symbol. Below code is equivalent to code as above in legacy way.

try
{
//some code here
}
catch (ArithmeticException|NumberFormatException ex)
{
 System.out.println("Exception Encountered " + ex);
 }

While applying above Java 7+ multi catch .We have to follow below rules:

  • Rule 1: Multi catch is for exceptions with different hierarchy.
  • Rule 2: Can not re-assign value to catch parameter in multi-catch.
  • Rule 3: In Java 7, Exception will not handle all exception.

Below are running example with legacy way of multi catch and Java 7+.

Multi cath block example

import java.util.Scanner;

public class MultiCatchTest {
/**
 * In the following code, we have to handle two different exceptions but take same action for both. So we needed to have two different catch blocks as of Java 6.0.
 * @param args
 */
	public static void main(String[] args) {
		 System.out.println("Please enter a integer value :");
		 Scanner scn = new Scanner(System.in);
	        try
	        {
	            int n = Integer.parseInt(scn.nextLine());
	            if (99%n == 0)
	                System.out.println(n + " is a factor of 99");
	        }
	        catch (ArithmeticException ex)
	        {
	            System.out.println("Arithmetic " + ex);
	        }
	        catch (NumberFormatException ex)
	        {
	            System.out.println("Number Format Exception " + ex);
	        }
	}
}

Output


Please enter a integer value :
0
Arithmetic java.lang.ArithmeticException: / by zero

Please enter a integer value :
3.5
Number Format Exception java.lang.NumberFormatException: For input string: "3.5"

Multi catch block example with (Java 7 +)

import java.util.Scanner;

public class MultiCatchTest7 {

	public static void main(String[] args) {
		  //After JAVA 7
        /**
         * single catch block to catch multiple exceptions by separating each with | (pipe symbol) in catch block.
         */
		 System.out.println("Please enter a integer value :");
		  Scanner scn = new Scanner(System.in);
        try
        {
            int n = Integer.parseInt(scn.nextLine());
            if (99%n == 0)
                System.out.println(n + " is a factor of 99");
        }
        catch (ArithmeticException|NumberFormatException ex)
        {
            System.out.println("Exception Encountered " + ex);
        }
	}
}

Output


Please enter a integer value :
0
Exception Encountered java.lang.ArithmeticException: / by zero

Please enter a integer value :
3.5
Exception Encountered java.lang.NumberFormatException: For input string: "3.5"

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

[Solved] javax.portlet.PortletException: Error occured during request processing: INSTANCE


This exception happened with web application or using rest services with Spring. In my case it was occurred with rest services using with Spring. It was because of conflict between old and new version of httpclient.jar and httpcore.jar. I was using latest version in my pom.xml while due to other jar dependency while deploy application added others older version jar.


javax.portlet.PortletException: Error occured during request processing: INSTANCE
    at org.springframework.web.portlet.DispatcherPortlet.doRenderService(DispatcherPortlet.java:805)
    at org.springframework.web.portlet.FrameworkPortlet.processRequest(FrameworkPortlet.java:536)
    at org.springframework.web.portlet.FrameworkPortlet.doDispatch(FrameworkPortlet.java:483)
    at javax.portlet.GenericPortlet.render(GenericPortlet.java:233)
    at com.liferay.portlet.FilterChainImpl.doFilter(FilterChainImpl.java:100)
    at com.liferay.portal.kernel.portlet.PortletFilterUtil.doFilter(PortletFilterUtil.java:64)
    at com.liferay.portal.kernel.servlet.PortletServlet.service(PortletServlet.java:111)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:72)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:73)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
    at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:593)
    at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:530)

Solution

I resolved this issue after reaching to lib folder of my web application deployment location:

Steps 1: Removed older version jars for httpclient and httpcore from lib directory.

Step 2: Restart the server.

INstance not found issue
Solution for javax.portlet.PortletException: Error occured during request processing: INSTANCE

My issue was resolved after following above two steps.

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

Java: Different Ways to writing in text File


In java there are several ways to write in to a file as below:

  1. BufferedWriter
  2. FileWriter
  3. FileOutputStream
  4. Files & Path (Java 7)
  5. FileChannel
  6. RandomAccessFile to write in specific position
  7. FileLock
  8. Temporary File

File writing by BufferedWriter

BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File.

It gives better performance when write operations are more because when more write operations then less IO operations.

String str = "Facing";
BufferedWriter writer = new BufferedWriter(new FileWriter(FILE));
writer.write(str);

writer.close();

when need to append more lines in file use File writer parameter with true to append more lines.

BufferedWriter writer = new BufferedWriter(new FileWriter(FILE, true));
writer.append(' ');
writer.append('Issues');
writer.append(' ');
writer.append('On');
writer.append(' ');
writer.append('IT');

writer.close();

File writing by FileWriter

FileWriter is the simplest way to write a file in java. FileWriter writes directly into Files and should be used only when number of writes are less. It also provides overloaded write method to write int, byte array and String to the File.

File file = new File(FILE);
FileWriter fr = null;
try {
   fr = new FileWriter(file);
   fr.write("Facing Issues On IT");
} catch (IOException e) {
   e.printStackTrace();
} finally {
try {
   fr.close();
} catch (IOException e) {
   e.printStackTrace();
}
}

File Writing by FileOutputStream

FileWriter and BufferedWriter are meant to write text to the file but when you need raw stream data to be written into file, you should use FileOutputStream to write file in java.

OutputStream os = null;
String data="FacingIssuesOnIt";
try {
	os = new FileOutputStream(new File(FILE));
	os.write(data.getBytes(), 0, data.length());
} catch (IOException e) {
	e.printStackTrace();
} finally {
try {
	os.close();
} catch (IOException e) {
	e.printStackTrace();
}
}

File Writing by Files

Java 7 introduced Files utility class and we can write a file using it’s write function, internally it’s using OutputStream to write byte array into file.

String data="FacingIssuesOnIt";
try {
	Files.write(Paths.get(FILE), data.getBytes());
} catch (IOException e) {
	e.printStackTrace();
}

File Writing by Channel

RandomAccessFile stream = new RandomAccessFile(FILE, "rw");
FileChannel channel = stream.getChannel();
String value = "FacingIssuesOnIT";
byte[] strBytes = value.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
buffer.put(strBytes);
buffer.flip();
channel.write(buffer);
stream.close();
channel.close();

File Writing on specific position

public void writeFileOnParticularPosition() throws IOException {
int data = 2018;
int position = 5;
RandomAccessFile writer = new RandomAccessFile(FILE, "rw");
writer.seek(position);
writer.writeInt(dataPos1);
writer.close();
}

File Writing to when Locked

RandomAccessFile stream = new RandomAccessFile(FILE, "rw");
FileChannel channel = stream.getChannel();

FileLock lock = null;
try {
lock = channel.tryLock();
} catch (final OverlappingFileLockException e) {
stream.close();
channel.close();
}
stream.writeChars("FacingIssuesOnIT");
lock.release();

stream.close();
channel.close();

File Writing to Temporary File

String toWrite = "FacingIssuesOnIT";
File tmpFile = File.createTempFile("test", ".tmp");
FileWriter writer = new FileWriter(tmpFile);
writer.write(toWrite);
writer.close();

Complete Example

In this example covered all the ways (BufferedWriter, FileWriter, FileOutputStream and Files) of file writing.

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileWritingWay {
	private static final String FILE = "C:\Users\saurabh.gupta1\Desktop\Test Data.java";

	/**
	 * Here in this class you will see different ways to write in file by java
	 *
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) {
		try {
			System.out.println("===========Java Write File using FIleWriter============");
			writeFileUsingFileWriter();
			System.out.println("===========Java Write File using BufferedWriter============");
			writeFileUsingBufferedWriter();
			System.out.println("===========Java Write File using FileOutputStream============");
			writeUsingOutputStream();
			System.out.println("===========Java 7 Write File using Files and Paths============");
			writeUsingFiles();
			System.out.println("===========Java 7 Write File using Files and Paths============");
			WriteToFileWhenLocked();
			System.out.println("===========Write on temporary File============");
			writeToTemporaryFile();
			System.out.println("===========Write File using FileChannel============");
			writeFileByFileChannel();
			System.out
					.println("===========Write File using RandomAccessFile to write in specific position============");
			writeFileOnParticularPosition();
			System.out.println("===========Write File using DataOutputStream============");
			writeFileusingDataoutputStream();
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	/**
	 * Use file writer when number of write operations are less
	 *
	 * @param data
	 */
	private static void writeFileUsingFileWriter() {
		File file = new File(FILE);
		FileWriter fr = null;
		try {
			fr = new FileWriter(file);
			fr.write("facingIssuesOnIT");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Use BufferedWriter when number of write operations are more It uses
	 * internal buffer to reduce real IO operations and saves time
	 *
	 * @param data
	 * @param noOfLines
	 */
	private static void writeFileUsingBufferedWriter() {
		try {
			String str = "Facing";
			BufferedWriter writer = new BufferedWriter(new FileWriter(FILE));
			writer.write(str);

			writer.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}

		// when need to append more lines in file use FileWrite with true as
		// below
		try {
			String str = "Facing";
			BufferedWriter writer = new BufferedWriter(new FileWriter(FILE, true));
			writer.append(' ');
			writer.append("Issues");
			writer.append(' ');
			writer.append("On");
			writer.append(' ');
			writer.append("IT");

			writer.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Use Streams when you are dealing with raw data
	 *
	 * @param data
	 */
	private static void writeUsingOutputStream() {
		OutputStream os = null;
		String data = "FacingissuesonIT";
		try {
			os = new FileOutputStream(new File(FILE));
			os.write(data.getBytes(), 0, data.length());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Use Files class from Java 1.7 to write files, internally uses
	 * OutputStream
	 *
	 * @param data
	 */
	private static void writeUsingFiles() {
		String data = "facingIssuesOnIT";
		try {
			Files.write(Paths.get(FILE), data.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void writeUsingPrintWiter() throws IOException {
		FileWriter fileWriter = new FileWriter(FILE);
		PrintWriter printWriter = new PrintWriter(fileWriter);
		printWriter.print("FacingIssuesOnIT");
		printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
		printWriter.close();
	}

	public static void writeFileusingDataoutputStream() throws IOException {
		String value = "facingIssuesOnIT";
		FileOutputStream fos = new FileOutputStream(FILE);
		DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
		outStream.writeUTF(value);
		outStream.close();

	}

	public static void writeFileOnParticularPosition() throws IOException {
		int data = 2018;
		int position = 5;
		RandomAccessFile writer = new RandomAccessFile(FILE, "rw");
		writer.seek(position);
		writer.writeInt(data);
		writer.close();
	}

	public static void writeFileByFileChannel() throws IOException {
		RandomAccessFile stream = new RandomAccessFile(FILE, "rw");
		FileChannel channel = stream.getChannel();
		String value = "FacingIssuesOnIT";
		byte[] strBytes = value.getBytes();
		ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
		buffer.put(strBytes);
		buffer.flip();
		channel.write(buffer);
		stream.close();
		channel.close();

	}

	public static void writeToTemporaryFile() throws IOException {
		String toWrite = "FacingIssuesOnIT";
		File tmpFile = File.createTempFile("test", ".tmp");
		FileWriter writer = new FileWriter(tmpFile);
		writer.write(toWrite);
		writer.close();
	}

	public static void WriteToFileWhenLocked() throws IOException {
		RandomAccessFile stream = new RandomAccessFile(FILE, "rw");
		FileChannel channel = stream.getChannel();

		FileLock lock = null;
		try {
			lock = channel.tryLock();
		} catch (final OverlappingFileLockException e) {
			stream.close();
			channel.close();
		}
		stream.writeChars("FacingIssuesOnIT");
		lock.release();

		stream.close();
		channel.close();
	}
}

References

 

Java :Different ways of Reading a text file


There are multiple ways of reading a text file in Java as below:

  1. BufferedReader
  2. FileReader
  3. Scanner
  4. Stream/Files (java 8): Read all file lines
  5. Paths (Java 8) : Read text file as String

Every way have something different as BufferedReader provides buffering of data for fast reading and Scanner provides parsing ability while we can use both BufferedReader and Scanner to read a text file line by line in Java.

Java 8 introduced Stream class java.util.stream which provides a lazy and more efficient way to read a file.

File Reading By BufferedReader

This method reads text from a character-input stream. It does buffering for efficient reading of characters, arrays, and lines.The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,


BufferedReader in = new BufferedReader(Reader in, int size);
try {
    File file = new File(FILE);
    BufferedReader br = new BufferedReader(new FileReader(file));
    String st;
    while ((st = br.readLine()) != null)
	System.out.println(st);
} catch (IOException ex) {
	ex.printStackTrace();
}

Note : In below code examples not follow usual practices of writing good code like flushing/closing streams, Exception-Handling etc, to reduce number of lines code for better understanding.

File Reading By FileReader

FileReader is convenient class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.


Constructors defined in this class are:
FileReader(File file) : Creates a new FileReader, given the File to read from.

FileReader(FileDescriptor fd): Creates a new FileReader, given the FileDescriptor to read from.

FileReader(String fileName): Creates a new FileReader, given the name of the file to read from.
try {
     FileReader fr = new FileReader(FILE);

     int i;
     while ((i = fr.read()) != -1)
	System.out.print((char) i);
} catch (IOException ex) {
	ex.printStackTrace();
}

File Reading By Scanner

A scanner can parse primitive types and strings using regular expressions and breaks its input into tokens using a delimiter pattern, which by default matches white space. The resulting tokens may then be converted into values of different types using the various next methods.

try {
	File file = new File(FILE);
	Scanner sc = new Scanner(file);

	while (sc.hasNextLine())
	System.out.println(sc.nextLine());
	} catch (Exception ex) {
	ex.printStackTrace();
	}

Read file by scanner without loop

File file = new File(FILE);
try {
	Scanner sc = new Scanner(file);
	// Use delimiter \Z for next line
	sc.useDelimiter("\Z");

	System.out.println(sc.next());
} catch (Exception ex) {
	ex.printStackTrace();
}

File Reading By Stream (Java8)

Files.readAllLines() method read all lines from a file and ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.
Bytes from the file are decoded into characters using the specified charset.


public static List readAllLines(Path path,Charset cs)throws IOException

This method recognizes the following as line terminators:
CARRIAGE RETURN followed by LINE FEED (u000D followed by u000A)
u000A, LINE FEED
u000D, CARRIAGE RETURN
List&amp;amp;lt;String&amp;amp;gt; lines = Collections.emptyList();
		try {
			lines = Files.readAllLines(Paths.get(FILE), StandardCharsets.UTF_8);
			Iterator&amp;amp;lt;String&amp;amp;gt; itr = lines.iterator();
			while (itr.hasNext())
				System.out.println(itr.next());
		} catch (IOException e) {
			e.printStackTrace();
		}

File Reading By Paths (Java8)

try {
			String data = new String(Files.readAllBytes(Paths.get(FILE)));
			System.out.println(data);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

Complete Example

In below example  covered all the above cases.

Test Data


Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
package com.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class FileReadingWay {
	private static final String FILE = "C:\Users\saurabh.gupta1\Desktop\Test Data.java";

	public static void main(String[] args) {
		FileReadingWay s = new FileReadingWay();
		System.out.println("===============Read File By Buffered Reader================");
		s.readFileByBufferedReader();
		System.out.println("===============Read File By File Reader================");
		s.readFileByFileReader();
		System.out.println("===============Read File By Scanner================");
		s.readFileByScanner();
		System.out.println("===============Read File By Scanner without Loop================");
		s.readFileByScannerWithOutLoop();
		System.out.println("===============Read All Files================");
		s.readFileByReadAllFiles();
		System.out.println("===============Read Text File and String================");
		s.readTextFileAsString();
	}

	private void readFileByBufferedReader() {
		try {
			File file = new File(FILE);

			BufferedReader br = new BufferedReader(new FileReader(file));

			String st;
			while ((st = br.readLine()) != null)
				System.out.println(st);
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	private void readFileByFileReader() {
		System.out.println();
		try {
			FileReader fr = new FileReader(FILE);

			int i;
			while ((i = fr.read()) != -1)
				System.out.print((char) i);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		System.out.println();
	}

	private void readFileByScanner() {

		try {
			File file = new File(FILE);
			Scanner sc = new Scanner(file);

			while (sc.hasNextLine())
				System.out.println(sc.nextLine());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void readFileByScannerWithOutLoop() {
		File file = new File(FILE);
		try {
			Scanner sc = new Scanner(file);
			// Use delimiter \Z for next line
			sc.useDelimiter("\Z");

			System.out.println(sc.next());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void readFileByReadAllFiles() {
		List&amp;amp;lt;String&amp;amp;gt; lines = Collections.emptyList();
		try {
			lines = Files.readAllLines(Paths.get(FILE), StandardCharsets.UTF_8);
			Iterator&amp;amp;lt;String&amp;amp;gt; itr = lines.iterator();
			while (itr.hasNext())
				System.out.println(itr.next());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void readTextFileAsString() {
		try {
			String data = new String(Files.readAllBytes(Paths.get(FILE)));
			System.out.println(data);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}

Output


===============Read File By Buffered Reader================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read File By File Reader================

Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read File By Scanner================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read File By Scanner without Loop================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read All Files================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read Text File and String================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 

References

 

[Solved]java.util.UnknownFormatConversionException: Conversion = ‘I’


java.util.UnknownFormatConversionException is runtime unchecked exception which throw when an unknown conversion is given. Unless otherwise specified, passing a null argument to any method or constructor in this class will cause a NullPointerException to be thrown.

  • UnknownFormatConversionException is sub class of IllegalFormatException.

Constructors

  • UnknownFormatConversionException(String s) : Constructs an instance of this class with the unknown conversion.

Example of UnknownFormatConversionException

In this below example by mistake use “Index” with specifiers sign (%) where considering ‘I’ as specifiers which is not match with predefined specifiers that’s what throwing this exception.

try
	     {
	     Scanner sc = new Scanner(new File("C:\Users\saurabh.gupta1\Desktop\testdata.txt"));
         int i=0;
	     while (sc.hasNextLine()) {
	    	//System.out.println(sc.nextLine());
	    	Scanner lineScanner = new Scanner(sc.nextLine());
	    	lineScanner.useDelimiter("|");
	    	if(i==0)
	    	{
	    	System.out.format("%-10Index%-10s%-10s%-10s%-10sn", sc.next(),sc.next(),sc.next(),sc.next(),sc.next());
	    	}
	    	else
	    	{
	    		i++;
	    		System.out.format("%-10d%-10s%-10s%-10s%-10sn", i,sc.next(),sc.next(),sc.next(),sc.next(),sc.next());
	    	}
	      }
	     }
	     catch(Exception ex)
	     {
	    	ex.printStackTrace();
	     }
	

Output

		 java.util.UnknownFormatConversionException: Conversion = 'I'
	at java.util.Formatter$FormatSpecifier.conversion(Unknown Source)
	at java.util.Formatter$FormatSpecifier.&amp;lt;init&amp;gt;(Unknown Source)
	at java.util.Formatter.parse(Unknown Source)
	at java.util.Formatter.format(Unknown Source)
	at java.io.PrintStream.format(Unknown Source)
	at com.userinput.JavaScannerParsingExample.main(JavaScannerParsingExample.java:45)

Solution

Always follow formatting specifiers rules as given in Java formatter.

https://docs.oracle.com/javase/10/docs/api/java/util/Formatter.html

References

https://docs.oracle.com/javase/8/docs/api/java/util/UnknownFormatConversionException.html

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

[Solved]java.util.NoSuchElementException


java.util.NoSuchElementException is runtime unchecked exception which throws by  nextElement() method of an Enumeration or nextXYZ() method of Scanner to indicate that there are no more elements in the enumeration or scanner.

Constructors

  • NoSuchElementException() : Constructs a NoSuchElementException with null as its error message string.
  • NoSuchElementException(String s) : Constructs a NoSuchElementException, saving a reference to the error message string s for later retrieval by the getMessage() method.

Example  NoSuchElementException

In below example NoSuchElementException occured because using useDelimiters(“\sGaurav\s“) while in test input using delimiters as “Saurabh”. In that case scanner will have only one text line and not split. When we retrieve data from scanner will throw this NoSuchElementException.

import java.util.Scanner;
public class JavaScannerParsingExample {
	public static void main(String[] args) {
		String input = "Facing Saurabh Issues Saurabh On Saurabh IT Saurabh 123 Saurabh 54 Saurabh";
	     Scanner s = new Scanner(input).useDelimiter("\s*Gaurav\s*");
	     System.out.println(s.next());
	     System.out.println(s.next());
	     System.out.println(s.next());
	     System.out.println(s.next());
	     System.out.println(s.nextInt());
	     System.out.println(s.nextInt());
	     s.close();
	}
}

Output

Facing Saurabh Issues Saurabh On Saurabh IT Saurabh 123 Saurabh 54 Saurabh
Exception in thread "main" java.util.NoSuchElementException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at com.userinput.JavaScannerParsingExample.main(JavaScannerParsingExample.java:11)

Solutions

  • In case of enumeration always check for hasNextElement() before use method next() to retrieve element of enumeration.
  • In case of Scanner always check for hasNext() before use method nextXYZ() to retrieve values from scanner.

References

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

[Solved]java.util.InputMismatchException


java.util.InputMismatchException which throw by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

  • InputMismatchException is runtime unchecked exception.
  • InputMismatchException is sub class of NoSuchElementException.

Constructors

  • InputMismatchException() : Constructs an InputMismatchException with null as its error message string.
  • InputMismatchException(String s): Constructs an InputMismatchException, saving a reference to the error message string s for later retrieval by the getMessage method.

Example

In below example create this java.util.InputMismatchException by passing some others type values other than expectation. For Example : age expected as integer value from console while passing as decimal value.

import java.util.Scanner;

public class JavaScannerExample {

	public static void main(String[] args) {
		// Create a Scanner object
		Scanner scanner = new Scanner(System.in); 

		try
		{
		//User different type of input from console
		System.out.println("Please enter user name:");
		String userName = scanner.nextLine();
		System.out.println("Please enter age:");
		int age = scanner.nextInt();
		System.out.println("Please enter salary:");
	    double salary = scanner.nextDouble();

	    //Output input by user
	    System.out.println("User Name: " + userName);
	    System.out.println("Age: " + age);
	    System.out.println("Salary: " + salary);
		}
		catch(Exception ex)
		{
			System.err.println("Entered user input are not match with required type:");
			ex.printStackTrace();
		}

	}

}
Please enter user name:
Saurabh Gupta
Please enter age:
13.5
Entered user input are not match with required type:
java.util.InputMismatchException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at java.util.Scanner.nextInt(Unknown Source)
	at java.util.Scanner.nextInt(Unknown Source)
	at com.userinput.JavaScannerExample.main(JavaScannerExample.java:28)

Solution

  • In such type scenarios where user interaction required always write code and ask input as scanner.nextLine();
  • Always validate values type before assign to variable.
  • If any mismatch found and throw above exception show message to insert value again as required format.

References

https://docs.oracle.com/javase/8/docs/api/java/util/InputMismatchException.html

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

[Solved] java.lang.IllegalArgumentException: “ABC”


java.lang.IllegalArgumentException is runtime unchecked exception. IllegalArgumentException throw as a preconditions check to indicate that a method has been passed an illegal or inappropriate argument.

IllegalArgumentException occurred generally in two cases:

  • IllegalArgumentException on preconditions check
  • IllegalArgumentException on chained exception

Constructors

  • IllegalArgumentException() :Constructs an IllegalArgumentException with no detail message.
  • IllegalArgumentException(String s) :Constructs an IllegalArgumentException with the specified detail message.
  • IllegalArgumentException(String message, Throwable cause) :Constructs a new exception with the specified detail message and cause.
  • IllegalArgumentException(Throwable cause) :Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

Example: IllegalArgumentException preconditions check

In below example validating percentage and email based on basic criteria and throwing generic message as “Bad Percentage” and “Invalid Email Address”.

public class IllegalArgumentExceptionExample {
public static void main(String[] args) {
      try
      {
    	  validatePercentage(50); //valid percentage
    	  validatePercentage(-20);//invalida percentage
      }
      catch(Exception ex)
      {
    	  ex.printStackTrace();
      }
      try
      {
    	  validateEmail("facingissuesonit@gmail.com"); //valid email
    	  validateEmail("facingissuesonit-gmail.com");//invalid email
      }
      catch(Exception ex)
      {
    	  ex.printStackTrace();
      }

	}
	public static void validatePercentage(int pct) {
	    if( pct < 0 || pct > 100) {
	         throw new IllegalArgumentException("Bad Percent");
	     }
	}
	public static void validateEmail(String email)
	{
	  if (!email.contains("@")) {
	      throw new IllegalArgumentException("Invalid Email Address");
	  }
	}
}

Output

java.lang.IllegalArgumentException: Bad Percent
	at com.exceptions.IllegalArgumentExceptionExample.validatePercentage(IllegalArgumentExceptionExample.java:44)
	at com.exceptions.IllegalArgumentExceptionExample.main(IllegalArgumentExceptionExample.java:23)
java.lang.IllegalArgumentException: Invalid Email Address
	at com.exceptions.IllegalArgumentExceptionExample.validateEmail(IllegalArgumentExceptionExample.java:51)
	at com.exceptions.IllegalArgumentExceptionExample.main(IllegalArgumentExceptionExample.java:33)

Example: IllegalArgumentException chained exception

In below example, consider a situation in which a method throws an IllegalArgumentException with message “passing Argument is not valid” but the actual cause of exception was an ArithmeticException because of an attempt to divide by zero The method will throw only IllegalArgumentException to the caller. So the caller would not come to know about the actual cause of exception and will see only generic message.

public class ChainedExceptionExample {

	public static void main(String[] args) {
		try {
			int totalAge = 500;
			int numberOfPerson = 0;

			int averageAge = averageAge(totalAge, numberOfPerson);

			System.out.println("Average Age :" + averageAge);
		} catch (Exception ex) {
			System.out.println(ex);
			ex.printStackTrace();
		}
	}

	public static int averageAge(int totalAge, int numberOfPerson) {
		int avarageAge;
		try {
			/**
			 * ArithmaticException can happen here because of value value
			 * NumberOfPerson as 0
			 */
			avarageAge = totalAge / numberOfPerson;
		} catch (Exception ex) {
			System.out.println(ex); // Actual Exception
			/**
			 * Exception Chaining here by relating this ArithmaticException to
			 * IllegalArgumentException
			 */
			throw new IllegalArgumentException("Passing argument is not valid", ex.getCause());
		}
	return avarageAge;
	}
}

Output

java.lang.ArithmeticException: / by zero
java.lang.IllegalArgumentException: Passing argument is not valid
java.lang.IllegalArgumentException: Passing argument is not valid
	at com.customexceptions.ChainedExceptionExample.averageAge(ChainedExceptionExample.java:33)
	at com.customexceptions.ChainedExceptionExample.main(ChainedExceptionExample.java:10)

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

Chained Exception


Prerequisite

Chained Exception allows to relate one exception with another exception, i.e one exception describes cause of another exception. Chained Exception is used in such type of situations.

In below example, consider a situation in which a method throws an IllegalArgumentException with message “passing Argument is not valid” but the actual cause of exception was an ArithmeticException because of an attempt to divide by zero The method will throw only IllegalArgumentException to the caller. So the caller would not come to know about the actual cause of exception and will see only generic message.

Constructors Of Throwable class

  • Throwable(Throwable cause) : Where cause is the exception that causes the current exception.
  • Throwable(String message, Throwable cause) : Where message is the exception message and cause is the exception that causes the current exception.

Methods Of Throwable class

  • getCause() method:This method returns actual cause of an exception.
  • initCause(Throwable cause) method:This method sets the cause for the calling exception.

Example of using Chained Exception

public class ChainedExceptionExample {
	public static void main(String[] args) {
		try {
			int totalAge = 500;
			int numberOfPerson = 0;

			int averageAge = averageAge(totalAge, numberOfPerson);

			System.out.println("Average Age :" + averageAge);
		} catch (Exception ex) {
			System.out.println(ex);
			ex.printStackTrace();
		}
	}
	public static int averageAge(int totalAge, int numberOfPerson) {
		int avarageAge;
		try {
			/**
			 * ArithmaticException can happen here because of value value
			 * NumberOfPerson as 0
			 */
			avarageAge = totalAge / numberOfPerson;
		} catch (Exception ex) {
			System.out.println(ex); // Actual Exception
			/**
			 * Exception Chaining here by relating this ArithmaticException to
			 * IllegalArgumentException
			 */
			throw new IllegalArgumentException("Passing argument is not valid", ex.getCause());
		}
		return avarageAge;
	}
}

Output

java.lang.ArithmeticException: / by zero
java.lang.IllegalArgumentException: Passing argument is not valid
java.lang.IllegalArgumentException: Passing argument is not valid
	at com.customexceptions.ChainedExceptionExample.testMethod1(ChainedExceptionExample.java:23)
	at com.customexceptions.ChainedExceptionExample.main(ChainedExceptionExample.java:9)

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

 

Java Exception Propagation


Prerequisite

Exception Propagation :  When an exception happens, propagation is the process where exception is dropped from top to bottom of stack until not caught by catch block or if no any catch block to handle it throw to JVM.

Ways to handle Exception Propagation in checked and unchecked exception are different.

  1. Exception Propagation in Unchecked Exceptions
  2. Exception Propagation in Checked Exceptions (throws)

Exception Propagation in Unchecked Exceptions

When a unchecked exception happens, Exception being dropped from to the top to the
bottom of the stack. If not caught once, the exception again drops down to the previous method and so on until it gets caught or until it reach the very bottom of the call stack. This is called exception propagation.

Note : By default, Unchecked Exceptions are forwarded in calling chain (propagated).

In the example below, exception occurs in method3() where it is not handled, so it is propagated to previous method2() where it is not handled, again it is propagated to method1() where exception is handled.
Exception can be handled in any method in call stack either in main() method, method1(), method2() or method3() .

public class UncheckedExceptionPropagation {
	public static void main(String[] args) {
		method1();
		System.out.println("Flow Completed..");
	}
	public static void method1()
	{
		try
		{
			method2();//Exception propagation to method1
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			System.out.println("Exception Handled Here..");
		}
	}
	public static void method2()
	{
		method3();//Exception propagation to method2
	}
	public static void method3()
	{
		int x=100/0;//ArithmeticException happen here
	}
}

Output

java.lang.ArithmeticException: / by zero
Exception Handled Here..	at com.customexceptions.UncheckedExceptionPropagation.method3(UncheckedExceptionPropagation.java:29)
	at com.customexceptions.UncheckedExceptionPropagation.method2(UncheckedExceptionPropagation.java:25)
	at com.customexceptions.UncheckedExceptionPropagation.method1(UncheckedExceptionPropagation.java:15)
	at com.customexceptions.UncheckedExceptionPropagation.main(UncheckedExceptionPropagation.java:7)

Flow Completed..

Exception Propagation in Checked Exceptions

When a checked exception happens, the propagation of exception does not happen and its mandatory to use throws keyword here. Only unchecked exceptions are propagated. Checked exceptions throw compilation error.

In example below, If we omit the throws keyword from the method3() and method2() functions, the compiler will generate compile time error. Because unlike in the case of unchecked exceptions, the checked exceptions cannot propagate without using throws keyword.

Note : By default, Checked Exceptions are not forwarded in calling chain (propagated).

import java.io.IOException;

public class CheckedExceptionPropagation {
	public static void main(String[] args) {

		method1();
		System.out.println("Flow Completed..");
	}
	public static void method1()
	{
		try
		{
			method2();//Exception propagation to method1
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			System.out.println("Exception Handled Here..");
		}
	}
	public static void method2() throws IOException
	{
		method3();//Exception propagation to method2
	}
	public static void method3() throws IOException
	{
		throw new IOException("Propagation Exception test");
	}
}

Output

java.io.IOException: Propagation Exception test
	at com.customexceptions.CheckedExceptionPropagation.method3(CheckedExceptionPropagation.java:31)
	at com.customexceptions.CheckedExceptionPropagation.method2(CheckedExceptionPropagation.java:27)
	at com.customexceptions.CheckedExceptionPropagation.method1(CheckedExceptionPropagation.java:17)
	at com.customexceptions.CheckedExceptionPropagation.main(CheckedExceptionPropagation.java:9)
Exception Handled Here..
Flow Completed..

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

Exception handling with method overriding


Before discussing about 4 rules to handle exception in overriding method. You should understand concepts of

Exception handling in override method these are 4 rules where you have to handle exceptions for child class according to given parent class scenarios:

4 Rules for Exception Handling in Overring Method
4 Rules for Exception Handling in Overring Method

Note : When you face any Java interview and test at least one or two questions surely will ask based on these cases to check you Exception Handling concepts and practical knowledge.

Case 1 : If parent-class method doesn’t declare any exception

  1. Child class overriding method can declare no exception in overriding method.

    Overriding Method No Exception throws
    Overriding Method No Exception throws
  2. Child class overriding method can declare unchecked exception in overriding method.

    Overriding Method Throws Unchecked Exception
    Overriding Method Throws Unchecked Exception
  3. Child class overriding method can declare strictly no checked exception in overriding method.

    Override method throws no checked exception
    Override method throws no checked exception

Case 2 : If parent-class method declares unchecked exception

  1. Child class overriding method can declare no exception in overriding method.

    Parent Uncheck child no excepton
    Parent Class Unchecked Exception Child Class No Exception
  2. Child class overriding method can declare any number of unchecked exception in overriding method.

    Parent Unchecked exception Child any Number Unchecked exception
    Parent Class method UncheckedException and Child Class overriding method unlimited Unchecked Exception
  3. Child class overriding method can declare strictly no checked exception in overriding method.

    Parent Class Unchecked Exception and Child class Checked Exception
    Parent Class Unchecked Exception and Child class overriding method Checked Exception not allow.

Case 3 : If parent-class method declares checked exception

  1. Child class overriding method can declare no exception in overriding method.

    Parent Class Method Checked Exception Child Class No Exception
    Parent Class Method Checked Exception Child Class Overriding Method No Exception
  2. Child class overriding method can declare same checked exception in overriding method.

    Parent Class Checked Exception Child Class same Checked Exception
    Parent Class method Checked Exception Child Class overriding method same Checked Exception
  3. Child class overriding method can declare sub-type of checked exception in overriding method.Parent class checked exception and child class sub class checked exception
  4. Child class overriding method can declare any number of unchecked exception in overriding method.Parent class checked exception child class any number unchecked exception

Case 4 : If parent-class method declares both checked & unchecked exceptions

  1. Child class overriding method can declare no exception in overriding method.

    Parent class checked and uncheked exception child no exception
    Parent class checked and un-cheked exception child class overriding method no exception
  2. Child class overriding method can declare same checked exception in overriding method.

    Parent class having checked and uncheck exception both and child class checked exception
    Parent class having checked and uncheck exception both and child class overriding method having same checked exception
  3. Child class overriding method can declare sub-type of checked exception in overriding method.

    Parent class having checked and uncheked exception child class having sub class of cheked exception
    Parent class having checked and uncheked exception child class overriding method having sub class of checked exception
  4. Child class overriding method can declare any number of unchecked exception in overriding method.

    Parent class having cheked and unchecked exception and child class having unlimited unchecked exception
    Parent class having chceked and unchecked exception and child class overriding method having unlimited unchecked exception

Conclusions

I have covered all scenarios for exception handling in overriding method:

  • If parent-class method doesn’t declare any exception, then child-class overriding-method can declare,
    • 1. No exception or
    • 2. Any number of unchecked exception
    • 3. but strictly no checked exception
  • If parent-class method  declare unchecked exception, then child-class overriding-method can declare,
    • 1. No exception or
    • 2. Any number of unchecked exception
    • 3. but strictly no checked exception
  • If parent-class method  declare unchecked exception, then child-class overriding-method can declare,
    • 1. No exception or
    • 2. Same checked exception or
    • 3. Sub-type of checked exception or
    • 4. any number of unchecked exception
  • All above conclusion hold true, even if combination of both checked & unchecked exception is declared in parent-class’ method

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

 

 

[Solved] java.lang.StackOverflowError


java.lang.StackOverflowError is sub class of java.lang.VirtualMachineError. JVM throws a stack overflow when application stack exhausted, due to deep recursion.

What is StackOverFlowError?

When a method call is invoked by a Java application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no space for a new stack frame then, the java.lang.StackOverflowError is thrown by the Java Virtual Machine (JVM).

Reasons to occurs java.lang.StackOverFlowError

  • Recursion : A method invokes itself during it’s execution and method calling stack reach to max limit of JVMExample 1
  • Circular Dependency on method calling. Example 2

A method may not declare such errors in its throw clause, because these errors are abnormal conditions that shall never occur.

Constructors

  • StackOverflowError(): Constructs a StackOverflowError with no detail message.
  • StackOverflowError(String s): Constructs a StackOverflowError with the specified detail message.

Recusrsion StackOverFlowError Example

In this below recursion factorial of number example , I have commented out the recursion terminating condition to create StackOverFlowError.

package com.exceptions.errors;

public class StackOverFlowErrorExample {

	public static void main(String[] args) {
		RecursionExample recursion=new RecursionExample();
		System.out.println(recursion.fact(7));
	}
}

class RecursionExample
{
	public int fact(int n){
//Uncomment this condition to recursion terminating condition
//	    if( n == 0 ){
//	        return 1;
//	    }
	    return n * fact(n-1);
	}
}

Output

Exception in thread "main" java.lang.StackOverflowError
	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
	at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18)
	at ......

Circular Dependency StackOverFlowError Example

In this example, we defined two classes, Company and Employee. The class Company contains one instance of the Employee class, while, the Employee class contains one instance of the Company class. Thus, we have a circular dependency between these two classes. Furthermore, each toString() method, invokes the corresponding toString() method of the other class, and so on, which results in a java.lang.StackOverflowError.

package com.exceptions.errors;

public class StackOverFlowExample2 {

	public static void main(String[] args) {
		Company company = new Company();
		System.out.println(company.toString());

	}
}

class Company {
	private int budget;
	private Employee employeeInstance = null;

	public Company() {
		budget = 0;
		employeeInstance = new Employee();
	}

	@Override
	public String toString() {
		return "FacingIssueOnIT : Company";
	}
}

class Employee {
	private int salary;
	private Company companyInstance = null;

	public Employee() {
		salary = 10;
		companyInstance = new Company();
	}

	@Override
	public String toString() {
		return "FacingIssueOnIT : Employee";
	}
}

Output

Exception in thread "main" java.lang.StackOverflowError
	at com.exceptions.errors.Employee.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:33)
	at com.exceptions.errors.Company.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:18)
	at com.exceptions.errors.Employee.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:33)
	at com.exceptions.errors.Company.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:18)
	at com.exceptions.errors.Employee.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:33)
	at com.exceptions.errors.Company.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:18)
	at com.exceptions.errors.Employee.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:33)
	at com.exceptions.errors.Company.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:18)
	at com.exceptions.errors.Employee.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:33)
	at com.exceptions.errors.Company.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:18)
	at com.exceptions.errors.Employee.&amp;amp;lt;init&amp;amp;gt;
....

How to deal with the StackOverflowError

  • In case of recursion, always apply terminating condition and that should execute in some cases so that method call not go to continuous call.
  • To inspect the stack trace and detect the repeating pattern of line numbers. These line numbers indicate the code being recursively called. Once you detect these lines, you must carefully inspect your code and understand why the recursion never terminates.
  • In case recursion and terminating condition are in place correctly.  You can increase the stack’s size, in order to allow a larger number of invocations. Default thread stack configuration depend on JVM some may equals to either 512KB, or 1MB. You can increase the thread stack size using the -Xss flag. This flag can be specified either via the project’s configuration, or via the command line. The format of the -Xss argument is:
     -Xss[g|G|m|M|k|K]

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:

[Solved] java.lang.OutOfMemoryError: Java heap space/PermGen/memory leak


java.lang.OutOfMemoryError is sub class of java.lang.VirtualMachineError. It throw when the JVM cannot allocate an object because of out of memory, and no more memory could be made available by the garbage collector. OutOfMemoryError objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.

Types of OutOfMemoryError in Java

Mainly two types of java.lang.OutOfMemoryError in Java:

    1.  The java.lang.OutOfMemoryError: Java heap space
    2. The java.lang.OutOfMemoryError: PermGen space

Though both of them occur because JVM ran out of memory they are quite different to each other and their solutions are independent of each other.

Constructors

  • OutOfMemoryError() :Constructs an OutOfMemoryError with no detail message.
  • OutOfMemoryError(String s):Constructs an OutOfMemoryError with the specified detail message.

OutOfMemoryError: Java heap space Example

In below example try to create java.lang.OutOfMemoryError by adding name “Saurabh Gupta” in infinite loop. It will add till the point as long as not throw java.lang.OutOfMemoryError.

package com.exceptions.errors;

public class OutOfMemoryErrorExample {

	public static void main(String[] args) {
		StringBuffer str=new StringBuffer("FacingIssuesOnIt");
	    int i=0;
		while(i==0)
		{
			str.append("Saurabh Gupta");
			System.out.println(i);
		}
	}
}

OutOfMemoryError StackTrace

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.util.Arrays.copyOf(Unknown Source)
	at java.lang.AbstractStringBuilder.ensureCapacityInternal(Unknown Source)
	at java.lang.AbstractStringBuilder.append(Unknown Source)
	at java.lang.StringBuffer.append(Unknown Source)
	at com.exceptions.errors.OutOfMemoryErrorExample.main(OutOfMemoryErrorExample.java:10)

In above example you see small program can also create OutOfMemoryError because just small wrong steps. as it’s having infinite loop and adding test continuously on same variable. You will get in depth knowledge of this in below paragraphs.

Reason to java.lang.OutOfMemoryError: PermGen space

PermGen can happen by two ways:

Reason 1:

In you are familiar with different generation of heap and garbage collection process, new , old and permanent generation of heap space. PermGen means Permanent Generation of the heap is used to store String pool and various Metadata required by JVM related classes, method and other java primitives.

In most of JVM default size of Perm Space is around “64MB”  which can reach easily by having too many classes and huge number of Strings in application.

Point to Remember: Setting heap size by -Xmx  no impact on OutOfMemory in perm space. To increase size of perm space specify size for permanent generation in JVM options as below.

“-XX: PermSize” and  “-XX: MaxPermSize”

export JVM_ARGS=”-Xmx1024m -XX:MaxPermSize=256m”

Reason 2:
Another reason of “java.lang.OutOfMemoryError: PermGen” is memory leak through Classloaders. Generally it’s happen in webserver and application servers like Glassfish, Weblogic, WebSphere or tomcat.

In application server used different class loaders are used to load different applications so that deploy and undeploy of one application without affecting of others application on same server. But during undeployment if container somehow keeps reference of any class loaded by application class loader then that class and all related class will not get garbage collected and quickly fill permGen space if you deploy and undeploy application many times.

Solutions to Resolve java.lang.OutOfMemoryError

Java.lang.OutOfMemoryError is a kind of error from JVM because of memory leak or objects are consuming memory but not releasing it. To identify root cause of problem required lots of investigation, like which object is taking memory, how much memory it is taking or finding dreaded memory leak.

Solve java.lang.OutOfMemoryError: Java heap space

  1. Easy way to solve OutOfMemoryError in java is to increase the maximum heap size by using JVM options. For increasing heap size in JVM better option to set  -Xmx to -Xms ration either 1:1 or 1:1.5 if you are setting heap size in your java application.

                   export JVM_ARGS=”-Xms1024m -Xmx1024m”

  2. If  still getting OutOfMemoryError after applying above solution.In this case, You can use profile tool to investigate memory leak and heap dump. For example :
    • Eclipse Memory Analyzer(MAT) to examine your heap dump.
    • Profiler like Netbeans or JProbe.

This is tough solution and requires some time to analyze and find memory leaks.

Solve java.lang.OutOfMemoryError: PermGen space

  1. Easy way to solve OutOfMemoryError: PermSpace is to increase heap size of Perm space by using JVM option   “-XX: MaxPermSize“. You can also specify initial size of Perm space by using  “-XX: PermSize” and keeping both initial and maximum Perm Space you can prevent some full garbage collection which may occur when Perm Space gets re-sized. For Example

          export JVM_ARGS=”-XX:PermSize=64M -XX:MaxPermSize=256m”

  2. If still getting OutOfMemoryError  after applying above solution. In this case, You can use profile tool to investigate memory leak and heap dump. For example :
    • Eclipse Memory Analyzer(MAT) to examine your heap dump.
    • Profiler like Netbeans or JProbe.

This is tough solution and requires some time to analyze and find memory leaks.

Solve OutOfMemoryError in PermGen Space In Tomcat

Tomcat  6.0 onward  provides memory leak detection feature which can detect many common memory leaks on web-app perspective For Example:

  • ThreadLocal memory leaks
  • JDBC driver registration
  • RMI targes
  • LogFactory
  • Thread spawned by web-apps etc.

You can check complete details on http://wiki.apache.org/tomcat/MemoryLeakProtection

Below are couple of free tools available in java space used to analyze heap and culprits of OutOfMemoryError.

Tools to investigate java.lang.OutOfMemoryError

  1. Eclipse Memory Analyzer(MAT) :  It help to analyze classloader leaks and memory leaks  by analyzing java heap dump.  It also help to consumption of less memory and identify exact suspect of memory leak.
  2. Visualgc (Visual Garbage Collector Monitoring Tool) : Attach this tool to you instrument hot spot JVM . It visually display all key data graphically including garbage collection, class loader and JVM compiler performance.
  3. Jhat (Heap Analyzer Tool) : After JDK-6 it’s part of new version of JDK now. We can use that command line utility to analyze heap dump in heap dump file by using “jmap”. When you execute below command and point your browser to port 7000 then you can start analyzing objects present in heap dump.
    Command : jthat -J-Xmx256m heapdump

References

https://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:

[Solved] java.lang.NumberFormatException: For input string “AB.C”


NumberFormatException is runtime Unchecked Exception. It’s sub class of IllegalArgumentsException. Generally it throws to indicate that the application has attempted to convert a String to one of the numeric types, but that the string does not have the appropriate format.

Constructors

  • NumberFormatException() : Constructs a NumberFormatException with no detail message.
  • NumberFormatException(String s) : Constructs a NumberFormatException with the specified detail message.

Example 1

In below example asking to enter integer value from console and that value further use for other steps. This example will throw ArithmaticException when enter value as 0 or throw NumberFormatException for any value except integer.

import java.util.Scanner;

public class NumberFormatExceptionExample {

public static void main(String[] args) {
System.out.println("Please enter a integer value :");
Scanner scn = new Scanner(System.in);
try
{
int n = Integer.parseInt(scn.nextLine());
if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
}
}

Output

Please enter a integer value :
3.56
Number Format Exception java.lang.NumberFormatException: For input string: "3.56"

Example 2

Here issue is passing string as non numeric value while parsing for Integer will throw NumberFormatException.

try
{
int age=Integer.parseInt("Twenty");}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}

Example 3

Here issue is passing string as numeric  value which out MAX range of integer that’s what throw NumberFormatException. In this case instead of using Integer.parseInt() use Long.parseLong(). 

try{
int phoneNumber=Integer.parseInt("1234567890");
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}

Solutions

Here are some common solutions for NumberFormatException:

  • Always check for numeric before using statement Integer.parseInt().
  • If expectation is big numeric value always use Long.parseLong().

References

https://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:

 

 

 

 

 

Java Custom Exception


We can create our own exception that is called as Custom Exception or User Defined Exception. Custom exceptions are used to customize the exceptions and messages according to user needs.

Steps to create Custom Exception

Below are steps to create custom exception:

  1. Create a class extends with one of the exceptions which are sub types of the java.lang.Exception class. Generally exception class always extends directly from the Exception class.
  2. Create a constructor with String parameter which is the detailed message of the exception.
  3. In this constructor, simply call the super constructor and pass the message.

Note : There is convection to use Custom Exception name ends with word ‘Exception’.

Steps Custom Exception or User Defined Exception
Custom Exception or User Defined Exception

In below example create a Custom Exception as EmployeeNotFoundException
which is extending class java.lang.Exception and create different constructors to handle exception with exception message and stack traces.

public class EmployeeNotFoundException extends Exception{
        //Constructor to throw exception with message
	public EmployeeNotFoundException(String message)
	{
		super(message);
	}
        //Constructor to throw exception with stack trace
	public EmployeeNotFoundException(Throwable cause)
	{
		super(cause);
	}
        //Constructor throw exception meth message and stack trace
	public EmployeeNotFoundException(String message,Throwable cause)
	{
		super(message,cause);
	}
}

Example to use Custom Exception

import java.util.Arrays;
import java.util.List;
public class CustomExceptionTest {
    public static void main(String[] args) throws EmployeeNotFoundException{
    String[] empArr ={"Saurabh", "Gaurav", "Shailesh", "Ankur", "Ranjith", "Ramesh"};
    List empList = Arrays.asList(empArr);
    String searchStr = "Rishabh";
	try {
	   if (!empList.contains(searchStr)) {
//Throw exception when emmployee name not match with existing list with customize message.
	throw new EmployeeNotFoundException("Employee not found in search");
	     }
	} catch (Exception ex) {
	 throw new EmployeeNotFoundException("Employee not found",ex);
	}
	}
}

Output

Exception in thread "main" com.customexceptions.EmployeeNotFoundException: Employee not found
    at com.customexceptions.CustomExceptionTest.main(CustomExceptionTest.java:16)
Caused by: com.customexceptions.EmployeeNotFoundException: Employee not found in search
    at com.customexceptions.CustomExceptionTest.main(CustomExceptionTest.java:13)

Conclusion

You have learn here :

  • What is Custom Exception or User-defined exception?
  • How to create Custom Exception or User-defined Exception?
  • and How to implement it?

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

 

[Solved] org.mockito.exceptions.misusing.UnnecessaryStubbingException


UnnecessaryStubbingException is runtime and sub class of MockitoException. Mockito JUnit Runner triggers UnnecessaryStubbingException only when none of the test methods use the stubbings. This means that it is ok to put default stubbing in a ‘setup’ method or in test class constructor. That default stubbing needs to be used at least once by one of the test methods.

Constructors

  • UnnecessaryStubbingException(String message) : Will throw exception with message.

Example

//code test:
 String result = translator.translate("Saurabh");

//Mock:
// <- stubbing used during code execution
 when(translator.translate("Saurabh")).thenReturn("Gupta");
// <- stubbing never used
when(translator.translate("Gaurav")).thenReturn("Gupta");

Solutions

It is highly recommended to remove unused stubbings to keep the codebase clean. You can opt-out from detecting unused stubbing using MockitoJUnitRunner.Silent() or MockitoRule.silent() (when you are using Mockito JUnit rules.

References

https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/UnnecessaryStubbingException.html

Know More

To know more about Junit, Mockito and exception solutions follow below links:

[Solved] org.mockito.exceptions.misusing.PotentialStubbingProblem


PotentialStubbingProblem is a RuntimeException and subclass of MockitoException. Mockito framework throws this exception when “stubbing arguments mismatch“.

Strict stubbing is a new opt-in feature for JUnit Rule and JUnit Runner to detect potential stubbing problems org.mockito.exceptions.misusing.PotentialStubbingProblem exception is thrown when mocked method is stubbed with some argument in test but then invoked with different argument in code.

This exception can occurred by many reasons:

  1. Mistake or typo in the test code, the argument(s) used when declaring stubbing’s is unintentionally different.
  2. Mistake or typo in the code under test, the argument(s) used in the code under test is unintentionally different.
  3. Intentional use of stubbed method with different argument, either in the test (more stubbing) or in code under test.

Constructors

  • PotentialStubbingProblem(String message) : Will throw exception with message.

Example

 //test method:
 given(mock.getSomething(200)).willReturn(something);

 //code under test:
// stubbing argument mismatch
 Something something = mock.getSomething(100);

Solutions

public class TestExample {
     @Rule
     public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);

     @Test public void exampleTest() {
         //Change the strictness level only for this test method:
         mockito.strictness(Strictness.LENIENT);

         //remaining test code
         given(mock.getSomething(200)).willReturn(something);
         //Will work
         Something something = mock.getSomething(100);

     }
 }

References

https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/PotentialStubbingProblem.html

Know More

To know more about Junit, Mockito and exception solutions follow below links: