Category Archives: Exception

[Solved] java.lang.IllegalStateException: The file is locked


Here this exception occurred because trying to connect H2 database through application while it’s already connected through eclipse data source explorer. That’s why when running application will through exception as “the file is locked.


java.lang.IllegalStateException: The file is locked: nio:C:/Users/saurabh.gupta1/testdb.mv.db [1.4.199/7]
    at org.h2.mvstore.DataUtils.newIllegalStateException(DataUtils.java:883) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.mvstore.FileStore.open(FileStore.java:172) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.mvstore.MVStore.(MVStore.java:390) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.mvstore.MVStore$Builder.open(MVStore.java:3343) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.mvstore.db.MVTableEngine$Store.open(MVTableEngine.java:162) ~[h2-1.4.199.jar:1.4.199]

Solutions

Follow below steps to resolve this issue. You just need to follow disconnect steps. Connect steps are just to reference to reach Data source explorer.

Steps to connect with H2 database with Eclipse

  • Go to eclipse
  • Go to tab Window -> View -> Type “Data” – Click on “Data Explorer”.
  • Select “Generic JDBC”
  • Fill properties as below.
  • Then click on Finish.

H2 database connection

Steps to disconnect database through eclipse

  • Go to “Data Explore”.
  • Expend Database connection.
  • Right click on H2DB database
  • Select option Disconnect.

Now run  application your issue get resolved.

You would like to see

Follow below link to see more JDBC, Hibernate and JPA issues solutions.

Advertisements

[Solved] com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure


  • com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure.
  • java.net.ConnectException: Connection refused.
  • SQLException: Connection refused or Connection timeout

All above exceptions occurred while connecting with database or communication issues because of one or more following causes:

  1. IP address or hostname in JDBC URL is wrong.
  2. Hostname in JDBC URL is not recognized by local DNS server.
  3. Port number is missing or wrong in JDBC URL.
  4. DB server is down.
  5. DB server doesn’t accept TCP/IP connections.
  6. DB server has run out of connections.
  7. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.

Solutions:

To solve the one or the other, follow the following suggestions:

  1. Verify and test them with ping.
  2. Refresh DNS or use IP address in JDBC URL instead.
  3. Verify it based on my.cnf of MySQL DB.
  4. Start the DB.
  5. Verify if MySQL is started without the --skip-networking option.
  6. Restart the DB and fix your code accordingly that it closes connections in finally.
  7. Disable firewall and/or configure firewall/proxy to allow/forward the port.

For Example :

For my case this exception occurred because database was not started.


Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:172)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:862)
    at com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:444)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:230)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:226)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at connection.MyConnection.getConnectionMain(MyConnection.java:59)
    at procedure_functions.StoredProcedureTest.main(StoredProcedureTest.java:42)
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:59)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:103)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:149)
    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:165)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:92)
    at com.mysql.cj.NativeSession.connect(NativeSession.java:152)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:982)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:852)
    ... 7 more
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:173)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:66)
    ... 10 more

More on JDBC

Follow below links to know more posts on JDBC and solving JDBC issues :

[Solved] java.lang.EnumConstantNotPresentException


Pre-requisite : Java: Enumeration Handling

This exception EnumConstantNotPresentException thrown when an application tries to access an enum constant by name and the enum type contains no constant with the specified name. This exception can be thrown by the API used to read annotations reflectively.

Example :

In this below example trying to read annotation by using reflection APIs. Here if api attempt to read an enum-valued member will result in a EnumConstantNotPresentException if the enum constant in the annotation is no longer present in the enum type. Compile everything and run ReadAnnotation. You will got C.

// TestEnum.java
public enum TestEnum {
    A, B, C;
}

// TestAnnotation.java
import java.lang.annotation.*;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
    TestEnum value();
}

// TestClass.java
@TestAnnotation(TestEnum.C)
public class TestClass {

}

// ReadAnnotation.java
public class ReadAnnotation {
    public static void main(String[] args) {
        System.out.println(TestClass.class.getAnnotation(TestAnnotation.class).value());
    }
}

To generate this exception, now remove the C from the TestEnum and recompile only TestEnum class preserving other classes as is. If you launch ReadAnnotation now, you will get:


Exception in thread "main" java.lang.EnumConstantNotPresentException: TestEnum.C
    at sun.reflect.annotation.EnumConstantNotPresentExceptionProxy.generateException(Unknown Source)
    at sun.reflect.annotation.AnnotationInvocationHandler.invoke(Unknown Source)
    at com.sun.proxy.$Proxy1.value(Unknown Source)
    at ReadAnnotation.main(ReadAnnotation.java:4)

References :

https://stackoverflow.com/questions/31261960/when-does-java-lang-enumconstantnotpresentexception-gets-thrown

Java :How to convert a stack trace to a string?


In this blog you will learn way to convert a stack trace to a String which includes all the Stack Trace message of an exception or error.

Why this conversion is required?

This conversion is required if you want to save the message in custom log file for further analysis of log message. The e.getMessage() in Java program only returns small portion of the error, but if you want to see the detailed error then StackTrace will give you complete detail about the error in the program.

Example

To convert stackTrace to a string using printWriter as input for stackTrace to convert in String.

import java.io.PrintWriter;
import java.io.StringWriter;

public class TestExample {

	public static void main(String[] args) {
		try
		{
			int y=5/0;
		}
		catch(Exception ex)
		{
			System.out.println(convertStackTraceToString(ex));
		}

	}
    /**
     * method to convert stack trace to String
     * @param ex
     * @return
     */
	private static String convertStackTraceToString(Exception ex) {

		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		ex.printStackTrace(pw);
		String sStackTrace = sw.toString();
		return sStackTrace;
	}

}

Output


java.lang.ArithmeticException: / by zero
    at com.exceptions.errors.TestExample.main(TestExample.java:11)

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

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

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


RedundantListenerException is RuntimeException and sub class of MockitoException. This occurred by Mockito framework when  instance of MockitoListener is being added to Mockito Framework and there is already a listener with this implementation type registered.

Note : It is ok to add multiple different implementations of the same listener interface type.

Constructors

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

Example

MockitoFramework.addListener(MockitoListener);

Solutions

If you are trying to add the listener but a listener of the same type was already added (and not removed) this method will throw RedundantListenerException. This is a safeguard to ensure users actually remove the listeners via removeListener</strong>. We do not anticipate the use case where adding the same listener type multiple times is useful.

References

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

Know More

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

[Solved]org.mockito.exceptions.base.MockitoException


MockitoException  is RuntimeException raised by Mockito framework to emit an error either due to Mockito, or due to the User. Mockito throws exception in form of stacktrace with suggested solutions.

StackTrace for Application calls:

StackTraceElement[] Throwable.getStackTrace()

StackTrace with Mockito and API calls:

StackTraceElement[] getUnifilteredStackTrace()

Constructors

  • MockitoException(String message) : Will throw exception with message.
  • MockitoException(String message, Throwable T) : Will throw exception with message and stacktrace.

Mockito Exception Subclasses

MockitoException Hierarchy
MockitoException Hierarchy

Example

In below example , using OngoingStubbing on mock object of Map interface where setting stub object for get() method which accept any input String and return response as String as set in thenReturn() method.

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.Map;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.stubbing.OngoingStubbing;

public class MockitoApplicationTester {

	@Test
	public void second_stubbing_throws_InCorrectUseOfAPI() throws Exception {
		// Mock of Map interface
		Map<String, String> map = mock(Map.class);

		OngoingStubbing<String> mapOngoingStubbing = when(map.get(anyString()));
		try {
			mapOngoingStubbing.thenReturn("1st stubbing");
			//This method will throw exception
			mapOngoingStubbing.thenReturn("2nd stubbing");
			Assert.assertEquals(map.get("Test"), "1st stubbing");
		} catch (MockitoException e) {
			StackTraceElement[] stacks = e.getStackTrace();
			for (StackTraceElement stack : stacks) {
				System.out.println(stack.getMethodName());
			}

			StackTraceElement[] ustacks = e.getUnfilteredStackTrace();
			for (StackTraceElement stack : ustacks) {
				System.out.println(stack.getMethodName());
			}
			throw e;

		}
	}

Output

org.mockito.exceptions.base.MockitoException:
Incorrect use of API detected here:
-> at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_IndexOutOfBoundsException(MockitoApplicationTester.java:48)

You probably stored a reference to OngoingStubbing returned by when() and called stubbing methods like thenReturn() on this reference more than once.
Examples of correct usage:
    when(mock.isOk()).thenReturn(true).thenReturn(false).thenThrow(exception);
    when(mock.isOk()).thenReturn(true, false).thenThrow(exception);

	at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_IndexOutOfBoundsException(MockitoApplicationTester.java:48)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>

Solutions

Above example is throwing MockitoException with message as “Incorrect use of API detected here”  because of thenReturn() method set two times value for single mock stub object. For solving above issue comment one of thenRetun() statement from try block.

References

https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/base/MockitoException.html#getUnfilteredStackTrace()

Know More

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

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


WrongTypeOfReturnValue is RuntimeException and Subclass of MockitoException.  It throws when :

  1.  It might occurred because of wrongly written multi-threaded tests.
  2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies with doReturn|Throw() family of methods. 

Constructors

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

Example

Below case to show you on what case Mockito will throw WrongTypeOfReturnValue .

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

import org.junit.Test;

public class NestedWhen {
	public class Bar {
	}

	public class Foo {
		Bar getBar() {
			return new Bar();
		}
	}

	public class Product {
		Bar bar;

		Product(Foo f) {
			bar = f.getBar();
		}
	}

	public class ProductService {
		Foo foo;

		ProductService(Foo f) {
			foo = f;
		}

		Product produce() {
			return new Product(foo);
		}
	}

	@Test
	public void nestedWhenTest() {
		Foo mfoo = mock(Foo.class);
		Product mpoo = mock(Product.class);
		ProductService productService = spy(new ProductService(mfoo));
		// throw WrongTypeOfReturnValue exception here!!!
		when(productService.produce()).thenReturn(mpoo);
	}
}

Output

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
NestedWhen$Product$$EnhancerByMockitoWithCGLIB$$4418933b cannot be returned by getBar()
getBar() should return Bar
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

	at com.facingissuesonit.mockito.MockitoTestExamples.NestedWhen.nestedWhenTest(NestedWhen.java:44)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)

Solutions

Here above code is throwing this exception because spy execute the real code by nature, so when calling “productService.produce()” the expression is actually executed and return a real Product. The constructor of Product takes the constructor arg “foo” which is a mock and it executes “f.getBar()”. This invocation is recorded by mockito because this “foo” instance is a mock.

Then when you want to return “mpoo”, mockito raises the exception WrongTypeOfReturnValue saying that the recorded invocation “foo.getBar()” cannot return a Product.

If you want to mock a partial mock, which you should avoid if possible. You need to use the following style for spies, this way Mockito can tell the spy instance to only record the invocation.

doReturn(mpoo).when(productService).produce();

References

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

Know More

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

 

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


InvalidUseOfMatchersException is RuntimeException and subclass of MockitoException. It throws when trying to push behavior on object which is not mock.

Constructors

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

Example

Here in below example mock Map interface and creating stub for get method to return fixed String for any type of String elements.


import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;

public class MockitoApplicationTester {

@Test
public void second_stubbing_throws_InCorrectUseOfAPI() throws Exception {
// Mock of Map interface
Map<String, String> mapMock = mock(Map.class);
Map<String, String> mapReal = new HashMap<String, String>();

//Issue is here because performing argument matcher without mock object
when(mapReal.get(anyString())).thenReturn("1st stubbing");

//Correct statement
when(mapMock.get(anyString())).thenReturn("1st stubbing");

Assert.assertEquals(mapMock.get("Test"), "1st stubbing");

}

}

Output


org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced argument matcher detected here:

-> at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_InCorrectUseOfAPI(MockitoApplicationTester.java:22)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_InCorrectUseOfAPI(MockitoApplicationTester.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)

Solutions

Here in above code is throwing this exception because using real object to create stub that’s what throwing “InvalidUseOfArgumentMatchersException“. To fix above this comment out wrong statement and execute again.

This exception can occurred by others ways also:

  1. This error might show up because you use argument matchers with methods that cannot be mocked.
  2. Stubbed and verified method can be used on final/private/equals()/hashCode() methods.
  3. Mocking methods declared on non-public parent classes is not supported.

References

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

Know More

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

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


MissingMethodInvocationException is RuntimeException and subclass of MockitoException. It generally throws when:

  1. It might occurs when() requires an argument which has to be ‘a method call on a mock. For example:                when(mock.getArticles()).thenReturn(articles);
  2. You try to stubbed/verified either of: final/private/equals()/hashCode() methods.
  3. Mocking methods declared on non-public parent classes is not supported.
  4. Inside when() you don’t call method on real object always call from mock or spy.

Constructors

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

Example

To complete example follow link Mockito + JUnit Tutorial

import static org.mockito.Mockito.spy;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.mockito.Mockito.*;
//@RunWith attaches a runner with the test class to initialize the test data
@RunWith(org.mockito.runners.MockitoJUnitRunner.class)
public class MathApplicationTestrSpy {
private CalculatorService calcService;

@Before
public void setUp(){
Calculator calculator = new Calculator();
calcService = spy(calculator);
//Issue is here because using actual object
when(calculator.add(20.0,10.0)).thenReturn(30.0);
}

@Test
public void testAdd(){
Assert.assertEquals(calcService.add(20.0, 10.0),30.0,0);
}

}

Output

org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

	at com.facingissuesonit.mockito.MockitoTestExamples.MathApplicationTestrSpy.setUp(MathApplicationTestrSpy.java:29)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)

Solutions

Here in above example trying stub on real object instead of mock and spy object. To solve this issue update code as below. For complete example please refer Mockito + JUnit TutorialMockito + JUnit Tutorial.


@Before
public void setUp(){
Calculator calculator = new Calculator();
calcService = spy(calculator);
//Issue is here because using actual object
//when(calcService.add(20.0,10.0)).thenReturn(30.0);

//Used Spy object
when(calculator.add(20.0,10.0)).thenReturn(30.0);
}

References

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

Know More

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

[Solved] java.time.temporal. UnsupportedTemporalType Exception: Unsupported field: YearOfEra


UnsupportedTemporalTypeException is sub class of java.time.DateTimeException which is runtime checked exception. UnsupportedTemporalTypeException indicates that a ChronoField or ChronoUnit is not supported for a Temporal class.

Constructors

  • UnsupportedTemporalTypeException(String message): Constructs a new UnsupportedTemporalTypeException with the specified message.
  • UnsupportedTemporalTypeException(String message, Throwable cause): Constructs a new UnsupportedTemporalTypeException with the specified message and cause.

 

Exception Example

Below is example to convert Legacy date(java.util.Date) to java.time.Instant and vice versa.

package java.time.temporal;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class UnsupportedTemporalTypeExceptionExample {

public static void main(String[] args) {
SimpleDateFormat utilDateTimeFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//Exception on below line to resolve this issue uncomment at end of line.
DateTimeFormatter java8DateTimeFormat=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");//.withZone(ZoneId.systemDefault());;
//Date to Instant
Date date=new Date();
Instant inst = date.toInstant();
System.out.println("Initial Date :"+utilDateTimeFormat.format(date));
System.out.println("Converted Instant :"+java8DateTimeFormat.format(inst));
//Instant To Date
Date newDate = Date.from(inst);
System.out.println("Converted Date :"+utilDateTimeFormat.format(newDate));
	}
}

Exception StackTrace


Initial Date :2018/08/04 08:11:53
Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
    at java.time.Instant.getLong(Unknown Source)
    at java.time.format.DateTimePrintContext.getValue(Unknown Source)
    at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(Unknown Source)
    at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(Unknown Source)
    at java.time.format.DateTimeFormatter.formatTo(Unknown Source)
    at java.time.format.DateTimeFormatter.format(Unknown Source)
    at com.date.Legacy2Java8DateTimeInteroprability.main(Legacy2Java8DateTimeInteroprability.java:26)

Issue

The Instant class doesn’t contain Zone information, it only stores timestamp in milliseconds from UNIX epoch, i.e. 1 Jan 1070 from UTC. So, formatter can’t print a date because date always printed for concrete time zone. To format an Instant a time-zone is required. Without a time-zone, the formatter does not know how to convert the instant to human date-time fields, and therefore throws an exception.

Solutions

The time-zone can be added directly to the formatter using withZone().You should set time zone to formatter and all will be fine.

in above example you can uncomment commented section as below to solve this issue.


DateTimeFormatter java8DateTimeFormat=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").withZone(ZoneId.systemDefault());;

some more ways to format date


DateTimeFormatter formatter =
    DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
                     .withLocale( Locale.UK )
                     .withZone( ZoneId.systemDefault() );

or

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.UK).withZone(ZoneOffset.UTC);

[Solved] java.sql.SQLException: No suitable driver


java.sql.SQLException: No suitable driver” occurred while connecting with Database by using JDBC api DriverManager.getConnection();

Sample Code

package com.fioit.examples.jdbc.connection;

import java.sql.DriverManager;
import java.sql.SQLException;

public class SQLServerConnection {

	public static void main(String[] args) {
		String db_url      = "jdbc:microsoft:sqlserver://HOST:1433;DatabaseName=DATABASE";
		String db_driver   = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
		String db_username = "USERNAME";
		String db_password = "PASSWORD";
		try
		{
		//Class.forName(db_driver);
		DriverManager.getConnection(db_url,db_username,db_password);
		}
//		catch(ClassNotFoundException ex)
//		{
//			ex.printStackTrace();
//		}
		catch(SQLException ex)
		{
			ex.printStackTrace();
		}

	}
}

Output


java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver://HOST:1433;DatabaseName=DATABASE
    at java.sql.DriverManager.getConnection(DriverManager.java:689)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at com.fioit.examples.jdbc.connection.SQLServerConnection.main(SQLServerConnection.java:16)

Issue

java.sql.SQLException: No suitable driver” occurred while connecting with Database by using JDBC api DriverManager.getConnection();

Solutions

  1. Include SQL deriver jar in your class path. For example for above case add SQLSerer driver jar in class path.
  2. Before Java 8 version: include below line for loading SQL driver

Class.forName(“sql.vendor.driver”);

For example: un comment Class.forName() line froom sample code.

In Java 8 or after version no need to write Class.forName() because it will load driver automatically based on connection URL.

More Issues Solution

For more other JAVA/JDBC issues solution follow link JAVA/JDBC Issues.

[Solved] com.microsoft.sqlserver.jdbc. SQLServerException: Invalid object name ‘dual’


Below com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name ‘dual’ exception example is for SQLServer for IBATIS and Hibernate but same can occurred in JDBC also.

Example



      select 1 from dual

Exception Stack

com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'dual'.
        at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1655)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:440)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:385)
        at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:191)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:166)

Issue

SQLServer does not support dual table.

Solution

In SQLServer there is no dual table. If you want to use that then there is no need from keyword. We can use it as below


select 1

Note : In MySQL and Oracle need a FROM clause to use where clause while in SQL Server allow WHERE clause directly with out FROM clause.

For Example:
Oracle
SELECT 123 FROM DUAL WHERE 1<2
SQL Server
SELECT 123 WHERE 1<2

More Issues Solution

For more other JAVA/JDBC issues solution follow link JAVA/JDBC Issues.

JDBC : Exception and Warning Handling


SQLException is Checked Exception it encounters an error when interacting with database , executing query on Databases etc. It throws instance of SQLException.

SQLException contains several kind information on a database access error or other errors which can help to determine the cause of error:

  • Description of Error : A string describing the error mesage. It can be retrieved by SQLException.getMessage().
  • SQLStateCode : These codes and their respective meanings have been standardized by ISO/ANSI and Open Group (XOPEN), although some codes have been reserved for database vendors to define for themselves. This String object consists of five alphanumeric characters. Retrieve this code by calling the method SQLException.getSQLState().
  • DatabaseMetaData: The DatabaseMetaData method getSQLStateType can be used to discover whether the driver returns the XOPEN type or the SQL:2003 type.
  • ErrorCode: This is an integer value identifying the error that caused the SQLException instance to be thrown. Its value and meaning are implementation-specific and might be the actual error code returned by the underlying data source. Retrieve the error by calling the method SQLException.getErrorCode().
  • Exception Chaining: If more than one error occurs, the exceptions are referenced through this chain. Retrieve these exceptions by calling the method SQLException.getNextException() on the exception that was thrown.
  • Cause: A SQLException instance might have a causal relationship, which consists of one or more Throwable objects that caused the SQLException instance to be thrown. To navigate this chain of causes, recursively call the method SQLException.getCause() until a null value is returned.

Constructors

  • SQLException() : Constructs a SQLException object.
  • SQLException(String reason) : Constructs a SQLException object with given reason.
  • SQLException(String reason, String SQLState) : Constructs a SQLException with given reason and SQLState.
  • SQLException(String reason, String SQLState, int vendorCode) : Constructs a SQLException with given reason ,SQLState and vendorCode.
  • SQLException(String reason, String SQLState, int vendorCode, Throwable cause) : Constructs a SQLException with given reason ,SQLState ,vendorCode and cause.
  • SQLException(String reason, Throwable cause) : Constructs a SQLException with given reason  and cause.
  • SQLException( Throwable cause) : Constructs a SQLException with given  cause.

SQLException Sub-classes

Our JDBC driver might throw a subclass of SQLException that corresponds to a common SQLState or a common error state that is not associated with a specific SQLState class value. This enables you to write more portable error-handling code. These exceptions are subclasses of one of the following classes:

  • BatchUpdateException
  • RowSetWarning
  • SerialException
  • SQLClientInfoException
  • SQLNonTransientException
  • SQLRecoverableException
  • SQLTransientException
  • SQLWarning
  • SynchFactoryException
  • SynchProviderException

SQLException Hierarchy

Lets focus on some most common happening SQLException:

BatchUpdateException

BatchUpdateException is thrown when an error occurs during a batch update operation. In addition to the information provided by SQLException, BatchUpdateException provides the update counts for all statements that were executed before the error occurred.

SQLClientInfoException

SQLClientInfoException is thrown when one or more client information properties could not be set on a Connection. In addition to the information provided by SQLException, SQLClientInfoException provides a list of client information properties that were not set.

SQLWarning

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions they simply alert the user that something did not happen as planned. For example, a warning might let you know that a privilege you attempted to revoke was not revoked. Or a warning might tell you that an error occurred during a requested disconnection.

A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object. If getWarnings returns a warning, you can call the SQLWarning method getNextWarning on it to get any additional warnings. Executing a statement automatically clears the warnings from a previous statement, so they do not build up. This means, however, that if you want to retrieve warnings reported on a statement, you must do so before you execute another statement.

Example of SQLWarning

The most common warning is a DataTruncation warning, a subclass of SQLWarning. All DataTruncation objects have a SQLState of 01004, indicating that there was a problem with reading or writing data. DataTruncation methods let you find out in which column or parameter data was truncated, whether the truncation was on a read or write operation, how many bytes should have been transferred, and how many bytes were actually transferred.

Complete Example for Handling SQLException and Warning

In below example i have created one JDBC utilities class which will help to handle SQLException, SQLWarning chained Exception related to Connection, Statement and ResultSet etc. Here you will also see like how we can skip particular warning and exceptions.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExceptionHandeling {

public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/facingissuesonitdb","root","root");
Statement stmt = conn.createStatement();
// Print JDBC Statement Warnings
JDBCUtilities.getWarningsFromStatement(stmt);
ResultSet rs = stmt.executeQuery("select * from employee");
// Print JDBC ResultSet Warnings
JDBCUtilities.getWarningsFromResultSet(rs);

while (rs.next()) {
System.out.println("ID :"+rs.getInt(1));
System.out.println("Name :"+rs.getString(2));
System.out.println("Job :"+rs.getString(3));
System.out.println("Salary :"+rs.getDouble(4));
System.out.println("*******************************");
	}
} catch (ClassNotFoundException ex) {
  System.err.println("SQL Driver is Not Found :"+ex.getMessage());
} catch (SQLException ex) {
  JDBCUtilities.printSQLException(ex);
 }
}
}

Utilities Class to Handle JDBC Exception and Warnings

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;

public class JDBCUtilities {
// Write method so that can handle SQL exception easily
public static void printSQLException(SQLException ex) {

for (Throwable e : ex) {
  if (e instanceof SQLException) {
     if (ignoreSQLException(((SQLException) e).getSQLState()) == false) {
	e.printStackTrace(System.err);
        System.err.println("SQLState: " + ((SQLException) e).getSQLState());
	System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
	System.err.println("Message: " + e.getMessage());

	Throwable t = ex.getCause();
	while (t != null) {
	  System.out.println("Cause: " + t);
	  t = t.getCause();
					}
				}
			}
		}
	}

	// Some Exception we can ignore so that no any action required.
	public static boolean ignoreSQLException(String sqlState) {

	if (sqlState == null) {
	 System.out.println("The SQL state code is not defined!");
	 return false;
	}

	// X0Y32: Jar file already exists in schema
	if (sqlState.equalsIgnoreCase("X0Y32"))
	return true;

	// 42Y55: Table already exists in schema
	if (sqlState.equalsIgnoreCase("42Y55"))
	return true;

	return false;
	}
	//Print Batch update Exception
	public static void printBatchUpdateException(BatchUpdateException b) {

	System.err.println("----BatchUpdateException----");
	System.err.println("SQLState:  " + b.getSQLState());
	System.err.println("Message:  " + b.getMessage());
	System.err.println("Vendor:  " + b.getErrorCode());
	//BatchUpdateException contains array of update counts that is similar to execute update
	System.err.print("Update counts:  ");
	int [] updateCounts = b.getUpdateCounts();

	for (int i = 0; i < updateCounts.length; i++) {
	        System.err.print(updateCounts[i] + "   ");
	    }
	}

	// retrieve result set related warnings
	public static void getWarningsFromConnection(Connection conn) throws SQLException {
		JDBCUtilities.printWarnings(conn.getWarnings());
	}

	// retrieve result set related warnings
	public static void getWarningsFromResultSet(ResultSet rs) throws SQLException {
		JDBCUtilities.printWarnings(rs.getWarnings());
	}

	// retrieve statement related warnings
	public static void getWarningsFromStatement(Statement stmt) throws SQLException {
		JDBCUtilities.printWarnings(stmt.getWarnings());
	}

	// This method is to print any warning from JDBC statement or result set
	public static void printWarnings(SQLWarning warning) throws SQLException {

	if (warning != null) {
	System.out.println("\n---Warning---\n");

	while (warning != null) {
	System.out.println("Message: " + warning.getMessage());
	System.out.println("SQLState: " + warning.getSQLState());
	System.out.print("Vendor error code: ");
	System.out.println(warning.getErrorCode());
	System.out.println("");
	warning = warning.getNextWarning();
			}
		}

	}
}

below is one SQlException output detail for one example where String value retrive with getInt()


ID :301
Name :Tester
Job :Rajesh
java.sql.SQLException: Bad format for number 'Jain' in column 4.
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
    at com.mysql.jdbc.ResultSetImpl.getDoubleInternal(ResultSetImpl.java:2549)
    at com.mysql.jdbc.ResultSetImpl.getDoubleInternal(ResultSetImpl.java:2488)
    at com.mysql.jdbc.ResultSetImpl.getDouble(ResultSetImpl.java:2449)
    at JDBCExceptionHandeling.main(JDBCExceptionHandeling.java:24)
SQLState: S1009
Error Code: 0
Message: Bad format for number 'Jain' in column 4.

For more other JAVA/JDBC issues solution follow link JDBC Issues and Solutions.

[Solved] java.lang.NoClassDefFoundError: org/apache/logging/log4j/core/config/Configurator


java.lang.NoClassDefFoundError is sub class of LinkageError. This exception thrown if Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

Constructor

  • NoClassDefFoundError():  Constructs a NoClassDefFoundError with no detail message.
  • NoClassDefFoundError(String s):  Constructs a NoClassDefFoundError with specific detail message.

Exception Stack Trace


Exception in thread "elasticsearch[2befByj][clusterService#updateTask][T#1]" java.lang.NoClassDefFoundError: org/apache/logging/log4j/core/config/Configurator
    at org.elasticsearch.common.logging.Loggers.setLevel(Loggers.java:149)
    at org.elasticsearch.common.logging.Loggers.setLevel(Loggers.java:144)
    at org.elasticsearch.index.SearchSlowLog.setLevel(SearchSlowLog.java:111)
    at org.elasticsearch.index.SearchSlowLog.(SearchSlowLog.java:106)
    at org.elasticsearch.index.IndexModule.(IndexModule.java:127)
    at org.elasticsearch.indices.IndicesService.createIndexService(IndicesService.java:440)
    at org.elasticsearch.indices.IndicesService.createIndex(IndicesService.java:413)
    at org.elasticsearch.cluster.metadata.MetaDataCreateIndexService$1.execute(MetaDataCreateIndexService.java:378)
    at org.elasticsearch.cluster.ClusterStateUpdateTask.execute(ClusterStateUpdateTask.java:45)
    at org.elasticsearch.cluster.service.ClusterService.executeTasks(ClusterService.java:634)
    at org.elasticsearch.cluster.service.ClusterService.calculateTaskOutputs(ClusterService.java:612)
    at org.elasticsearch.cluster.service.ClusterService.runTasks(ClusterService.java:571)
    at org.elasticsearch.cluster.service.ClusterService$ClusterServiceTaskBatcher.run(ClusterService.java:263)
    at org.elasticsearch.cluster.service.TaskBatcher.runIfNotProcessed(TaskBatcher.java:150)
    at org.elasticsearch.cluster.service.TaskBatcher$BatchedTask.run(TaskBatcher.java:188)
    at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:575)
    at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.runAndClean(PrioritizedEsThreadPoolExecutor.java:247)
    at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.run(PrioritizedEsThreadPoolExecutor.java:210)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.apache.logging.log4j.core.config.Configurator
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 21 more

Issue

Lets focus on particularly on this exception. This exception was occurred because trying to use Spring Boot with Elasticsearch framework. ElasticsearchTemaplate framework internally use log4j dependency which was not included on pom.xml

Solutions

To resolve this issue include below dependency in you pom.xml to add log4j2 jar to your application.


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
   

More Issues Solution

For more other JAVA/JDBC issues solution follow link JAVA/JDBC Issues.

[Solved] JDBC : java.sql.SQLSyntaxErrorException: Unknown database ‘database_name’


java.sql.SQLSyntaxErrorException is unchecked runtime exception which is sub class of SQLException. Herejava.sql.SQLSyntaxErrorException: Unknown database database_name”  exception occurred when connecting to database schema by JDBC. Please check below for more detail.

Sample Code

try
{
Class.forName("com.mysql.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/FacingIssuesOnITDB", "root", "facingissuesonit");
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}

Output


java.sql.SQLSyntaxErrorException: Unknown database 'facingissuesonitdb'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:862)
at com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:444)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:230)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:226)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.fioit.examples.jdbc.connection.MyConnection.getConnectionMain(MyConnection.java:59)
at com.fioit.examples.jdbc.crud.CRUDOperation.main(CRUDOperation.java:20)

Issue

Above issue “java.sql.SQLSyntaxErrorException: Unknown database database_name” occurred because no schema exist in MySQL database with name facingissuesonitdb.

Solution

In JDBC always handle java.sql.SQLException in your connection code also because if any issue happen for java.sql.SQLSyntaxErrorException can catch by SQLException block.

More Issues Solution

For more other JAVA/JDBC issues solution follow link JDBC Issues and Solutions.

[Solved] Maven: No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK


This maven exception occurs  when your Window/Unix environment variable for JAVA_HOME and PATH are pointing to JRE instead of JDK. That’s why maven will not compile code and throw below exception.

Problem

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building SpringBootApp 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.5.2/maven-install-plugin-2.5.2.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.5.2/maven-install-plugin-2.5.2.pom (7 KB at 2.3 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-plugins/25/maven-plugins-25.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-plugins/25/maven-plugins-25.pom (10 KB at 10.2 KB/sec)
[INFO]
[INFO] --- maven-resources-plugin:3.0.1:resources (default-resources) @ SpringBootApp ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ SpringBootApp ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to D:\Saurabh Gupta\facingIssuesOnIT\SpringBootApp\target\classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.342 s
[INFO] Finished at: 2018-05-28T15:59:31+05:30
[INFO] Final Memory: 20M/209M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project SpringBootApp: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Solutions

To resolve this issue you can follow below steps by solving command prompt or Eclipse.

Command Prompt

How to Configure Maven in Window and Linux?

Eclipse

  • Right click on project -> Select Properties
  • Select Java Build Path-> Libraries Tab -> Click on Add Library
  • Refer below link for reference.

Eclipse : How to set java path of JDK/JRE?

[Solved] Tomcat : java.net.BindException: Address already in use: bind


This is exception occurs when using port for tomcat server is already used and not closed yet.

Sometimes when eclipse hang and you directly close eclipse by task manager then eclipse close but tomcat process still running. When you open Eclipse again and try to run tomcat to deploy application. On that time you will get below exception as “java.net.BindException: Address already in use“.

Problem

org.apache.catalina.LifecycleException: Failed to start component [Connector[HTTP/1.1-8080]]
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.StandardService.addConnector(StandardService.java:225) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.addPreviouslyRemovedConnectors(TomcatWebServer.java:256) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
	at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.start(TomcatWebServer.java:198) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.startWebServer(ServletWebServerApplicationContext.java:300) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:162) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553) [spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
	at com.fiot.controller.Example.main(Example.java:17) [classes/:na]
Caused by: org.apache.catalina.LifecycleException: Protocol handler start failed
	at org.apache.catalina.connector.Connector.startInternal(Connector.java:1020) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	... 13 common frames omitted
Caused by: java.net.BindException: Address already in use: bind
	at sun.nio.ch.Net.bind0(Native Method) ~[na:1.8.0_151]
	at sun.nio.ch.Net.bind(Unknown Source) ~[na:1.8.0_151]
	at sun.nio.ch.Net.bind(Unknown Source) ~[na:1.8.0_151]
	at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source) ~[na:1.8.0_151]
	at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source) ~[na:1.8.0_151]
	at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:210) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:1150) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:591) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.connector.Connector.startInternal(Connector.java:1018) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	... 14 common frames omitted

2018-05-28 15:36:23.875  INFO 12964 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2018-05-28 15:36:23.898  INFO 12964 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-05-28 15:36:23.900 ERROR 12964 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

Solutions

Please follow below steps to resolve this issue.

Window

  • Got to (Open) Command Prompt (Press Window +R) or type cmd on run.
  • Get running process for port on command prompt.

netstat -aon |find /i “listening” |find “PortNumber

  • Kill Process running for port.

taskkill /F /PID ProcessNumber

 

[Solved] java.lang.IllegalStateException: No match found : Regular Expression


java.lang.IllegalStateException is most common Runtime Exception and Unchecked Exception . It throws by JVM when trying to access object methods which are not allowed on certain cases.

In below example matcher.group(1) throwing IllegalStateException as “not match” . In below case as java.lang.Regex first we should call to matcher.find() method to get match in text for specific regular expression then based on matcher.group() we can get match text.

package com.test.exceptions;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpressionTest {

	public static void main(String[] args) {
		String text = "Facing Issues on IT";
		Pattern pattern = Pattern.compile("\\w");
		Matcher matcher = pattern.matcher(text);
		if (matcher != null) {
			System.out.println(matcher.group(1));//Exception on this point
			System.out.println("Match Count :" + matcher.groupCount() +matcher.find());
		}
	}
}

Output

Exception in thread "main" java.lang.IllegalStateException: No match found
	at java.util.regex.Matcher.group(Unknown Source)
	at com.test.exceptions.RegularExpressionTest.main(RegularExpressionTest.java:13)

Solution 

In below code match.find() not called before matcher.group(1) that’s why throwing IllegalStateException.

Summary

  • Explain about IllegalStateException and Example
  • For Regular Expression in java.lanag.Regex what need to take care.
  • How to solve it.

 

[Solved] CloneNotSupportedException


java.lang.CloneNotSupportedException throws when object’s class does not implement the cloneable interface and  clone method in class Object has been called to clone an object.
Some applications that override the clone method can also throw this exception to indicate that an object could not or should not be cloned.

Cloneable is marker interface which is not having any method to implement. When implement marker interface in class it indicate to JVM how to treat with this objects.
For more info about marker interface , it’s type and how to create check below link.

Marker Interface in Java, Use and Custom Marker Interface

clone() is protected method of object class which is super class of all the classes. if need to use clone() method have to override it .

Constructors :

  • CloneNotSupportedException()

Create a CloneNotSupportedException object with no detail message.

  • CloneNotSupportedException(String message)

Create a CloneNotSupportedException object with  exception detail message.

Example

In below example creating clone object of Employee class from object there is no any compile time error because we have override clone method of Object Class in Employee class but it will throw CloneNotSupportedException while execution because as per

Contract : if cloneable interface is implemented then only clone method will call otherwise  JVM will throw CloneNotSupportedException.

Here we are doing Shallow cloning of object. For more info on shallow and deep cloning follow below link.

Employee Class

public class Employee {
private String firstName;
private String lastName;
private int age;
private double salary;
private Address address;

public Employee(String firstName, String lastName, int age, double salary, Address address) {
	super();
	this.firstName = firstName;
	this.lastName = lastName;
	this.age = age;
	this.salary = salary;
	this.address = address;
}
public String getFirstName() {
	return firstName;
}
public void setFirstName(String firstName) {
	this.firstName = firstName;
}
public String getLastName() {
	return lastName;
}
public void setLastName(String lastName) {
	this.lastName = lastName;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}
public double getSalary() {
	return salary;
}
public void setSalary(double salary) {
	this.salary = salary;
}
public Address getAddress() {
	return address;
}
public void setAddress(Address address) {
	this.address = address;
}

@Override
public String toString() {
	return "Employee [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", salary=" + salary
			+ ", address=" + address + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException {
	return super.clone();
}

}


Address Class


public class Address {
	private String addressLine1;
	private String city;
	private String state;
	private String contry;
	private String pincode;

	public Address(String addressLine1, String city, String state, String contry, String pincode) {
		super();
		this.addressLine1 = addressLine1;
		this.city = city;
		this.state = state;
		this.contry = contry;
		this.pincode = pincode;
	}

	public String getAddressLine1() {
		return addressLine1;
	}

	public void setAddressLine1(String addressLine1) {
		this.addressLine1 = addressLine1;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getContry() {
		return contry;
	}

	public void setContry(String contry) {
		this.contry = contry;
	}

	public String getPincode() {
		return pincode;
	}

	public void setPincode(String pincode) {
		this.pincode = pincode;
	}

	@Override
	public String toString() {
		return "Address [addressLine1=" + addressLine1 + ", city=" + city + ", state=" + state + ", contry=" + contry
				+ ", pincode=" + pincode + "]";
	}

}


Test for ClassNotSupportedException


public class CloneExample {

	public static void main(String[] args) {
		Address address = new Address("Next to Metro Station", "Noida", "UP", "India", "201301");
		Employee employee = new Employee("Saurabh", "Gupta", 30, 50000, address);
		System.out.println("Employee Object Before Clone :");
		System.out.println(employee);
		try {
                        System.out.println("Employee Object After Clone :");
			Employee employeeCopy = (Employee) employee.clone();

			System.out.println(employeeCopy);
		} catch (CloneNotSupportedException ex) {
			ex.printStackTrace();
		}

	}

}


Output

Employee Object Before Clone :
Employee [firstName=Saurabh, lastName=Gupta, age=30, salary=50000.0, address=Add
ress [addressLine1=Next to Metro Station, city=Noida, state=UP, contry=India, pi
ncode=201301]]
Employee Object After Clone :
java.lang.CloneNotSupportedException: Employee
	at java.lang.Object.clone(Native Method)
	at Employee.clone(Employee.java:55)
	at CloneExample.main(CloneExample.java:11)

Solutions :

To solve this CloneNotSupportedException we have to implement cloneable interface in Employee class as below and run this program again.

public class Employee implements Cloneable<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>{

}

Summary :

  • Explain about CloneNotSupportedException by example and how it happen.
  • Constructors of CloneNotSupportedException.
  • How to fix CloneNotSupportedException.
  • Cloneable Marker Interface.

References :

https://docs.oracle.com/javase/8/docs/api/java/lang/CloneNotSupportedException.html

[Solved] ClassNotFoundException: com.mysql.jdbc.Driver


java.lang.ClassNotFoundException is Checked Exception which is subclass of  java.lang.ReflectiveOperationException. This  is thrown when application load a class by String name whose definition is not found. This exception occurs by below methods :

  • The forName method in the class Class.

                 Class.forName(java.lang.String)

  • The findSystemClass method in the class ClassLoader.

                ClassLoader.findSystemClass()

  • The loadClass method in class ClassLoader.

                ClassLoader.loadClass(java.lang.String, boolean)

 Difference between Class.forName() and ClassLoader.loadClass()

Example 1: ClassNotFoundException

Below is example of connecting with database and retrieve data from sql table. This will throw ClassNotFoundException because sql driver jar is not in classpath. After this example also mentioned solution.

package example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ClassNotFoundException1 {

	public static void main(String[] args) {
		try {
			Class.forName("com.mysql.jdbc.Driver");

			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/university", "root", "");

			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select name from employee");
			String dbtime;
			while (rs.next()) {
				dbtime = rs.getString(1);
				System.out.println(dbtime);
			}

			con.close();

		} catch (ClassNotFoundException | SQLException e) {
			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
		}

	}

}

Output:

Connection Failed! Check output console
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
	at java.net.URLClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Unknown Source)
	at example.ClassNotFoundException1.main(ClassNotFoundException1.java:13)

Solutions:

For solving ClassNotFoundException by Class.ForName() method  considering above example to load MySQL driver same way you can follow for other classes and different DB drivers.

Solution in Eclipse :Follow below steps :

  • Right click your project folder and open up Properties.
  • From the right panel, select Java Build Path then go to Libraries tab.
  • Select Add External JARs to import the MySql driver.
  • From the right panel, select Deployment Assembly.
  • Select Add…, then select Java Build Path Entries and click Next.
  • You should see the SQL driver on the list. Select it and click first.

Tomcat :

If directly running from tomcat.Just copy the MySql-Connector.jar into Tomcat’s lib folder/directory, and then remove the jar from the webApp’s lib folder, and then, run the project.

Summary :

  • Define what is ClassNotFoundException.
  • What are methods throws ClassNotFoundException?
  • Example for ClassNotFoundException.
  • How to fix ClassNotFoundException in Eclipse and Tomcat.

[Solved] ClassCastException :A cannot be cast to B : Example


java.lang.ClassCastException is RuntimeException and Unchecked Exception which throws when code has attempted to cast an object to a subclass or class of which it is not an instance.

How to Fix ClassCastException ?

  • Always careful when try to cast an object of a class into another class. Make sure that new  type class belongs to one of its parent classes.
  • Use Generics to prevent ClassCastException because Generics provide compile time checks to develop type-safe applications so that issue identified on compile time.

Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.

Example :
Below are two example of ClassCastException where type casting an objet to different type which is not sub class of object class.

Example 1: Here first converting Integer Object to Object class which is parent class of all classes and then after type casting object of Object class to String Object. Which not compatible with Integer class and not sub class of Integer that’s why throwing ClassCastException.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ClassCastExceptionExample {

	public static void main(String[] args) {
		/**
		 * when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.
	 */
		try
		{
		Object object= new Integer(10);
		System.out.println((String)object);
		}
		catch(ClassCastException ex)
		{
			ex.printStackTrace();
		}
	}

}

Example 2:
Here we  are trying to type cast an object of class A into an object of class B, and they aren’t compatible, we will get a class cast exception.

Let’s think of a collection of classes from below example

class A {}
class B extends A {…}
class C extends A {…}
We can cast any of these things to Object, because all Java classes inherit from Object.
We can cast either B or C to A, because they’re both “kinds of” A
We can cast a reference to an A object to B only if the real object is a B.
We can’t cast a B to a C even though they’re both A’s on that point will throw type cast exception.

public class A
{
}
public class B extends A
{
}
public class C extends A
{
}

package example;

public class ClassCastExceptionExample {

	public static void main(String[] args) {		

		try {
         A a=new A();
         A b=new B();
         A c=new C();

         B d=(B)b;
         B e=(B)c;// Exception on that point

		} catch (ClassCastException ex) {
			ex.printStackTrace();
		}
	}

}

Output:

java.lang.ClassCastException: example.C cannot be cast to example.B
	at example.ClassCastExceptionExample.main(ClassCastExceptionExample.java:27)

[Solved] Exception UnsupportedOperationException Example


java.lang.UnsupportedOperationException is RuntimeException and Unchecked Exception which expected to thrown by JVM(Java Virtual Machine) when try to perform an “optional operation” which is not allowed an object .

The Java framework contains plenty of these, especially in the Collections framework. For example “add” is an optional operation, because immutable collections should not allow it. Throwing UnsupportedOperationException is exactly what you should do if you don’t want to write one of these methods.

Constructors :

  • UnsupportedOprationException() : Constructs an UnsupportedOperationException with no detail message.
  • UnsupportedOprationException(String message) : Constructs an UnsupportedOperationException with specified detail message.
  • UnsupportedOprationException(String message, Throwable cause) : Constructs an UnsupportedOperationException with specified detail message and cause.
  • UnsupportedOprationException(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 :

In below example problem is List returned from Arrays.AsList() is not like java.util.ArrayList. Arrays.asList() returns a java.util.Arrays$ArrayList which is an immutable list. You can not add or remove any element from this list otherwise will get java.lang.UnsupportedOperationException Exception.

package exceptionhandeling;

import java.util.Arrays;
import java.util.List;

public class UnsupportedOperationException {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//Convert Array to LIst
		List empList=Arrays.asList(empArr);
		/**
		 * By the time you get to the remove(i) statement, list is no longer a java.util.ArrayList.
		 * When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is an immutable list. You cannot add to it and you cannot remove from it.

		 * Not every List implementation support add method because Arrays.asList() returned
		 * immutable list of fixed size
		 */
		for(String emp:empList)
		{
			empList.add("Sachin");
			System.out.println(emp);
		}

	}

}

Output:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(Unknown Source)
	at java.util.AbstractList.add(Unknown Source)
	at example.UnsupportedOperationExceptionExample.main(UnsupportedOperationExceptionExample.java:21)

[Solved] ArrayIndexOutOfBoundException in JAVA


java.lang.ArrayindexOutOfboundsException is Runtime and Unchecked Exception. It’s subclass of java.lang IndexOutOfBoundsException.

ArrayIndexOutOfBoundsException is most common error in Java Program. It throws when an array has been accessed with an illegal index either negative or greater than or equal to the size of the array.

Points To Remember:

  •  Array index starts at zero and goes to length – 1, for example in an integer array int[] counts= new int[20], the first index would be zero and last index out be 19 (20 -1)
  • Array index cannot be negative, hence counts[-1] will throw java.lang.ArrayIndexOutOfBoundsException.
  • The maximum array index can be Integer.MAX_VALUE -1 because array accept data type of index is int and max allowed value for int is Integer.MAX_VALUE.

Constructors:

  • ArrayIndexOutOfBoundsException() : Constructs an  ArrayIndexOutOfBoundsException with no detail message.
  • ArrayIndexOutOfBoundsException(int index) : Constructs a new ArrayIndexOutOfBoundsException class with an argument indicating the illegal index.
  • ArrayIndexOutOfBoundsException(String s) : Constructs an ArrayIndexOutOfBoundsException class with the specified detail message.

Example :

public class ArrayOutOfBoundException {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//No of employee in array
		//Will through IndexOuhtOfBoundException because array having only six element of index 0 to 5
		try
		{
		String name=empArr[8];
		System.out.println("Employee :"+empArr[8]);
		}
		catch(ArrayIndexOutOfBoundsException ex)
		{
			ex.printStackTrace();
		}
	}
}

Output:

java.lang.ArrayIndexOutOfBoundsException: 8
	at example.ArrayIndexOutOfBoundsException.main(ArrayIndexOutOfBoundsException.java:11)<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

[Solved] java.lang.ArithmeticException: / by zero in JAVA


java.lang.ArithmeticException is Unchecked exception and sub class of java.lang.RuntimeException. It’s thrown when an exceptional condition occurred in Arithmetic Operations. It can also occurred by virtual machine as if suppression were disabled and /or the stack trace was not writable.

Constructors:

  • ArithmeticException() : Constructs an ArithmeticException with no detail message.
  • ArithmeticException(String s) : Constructs an ArithmeticException with the specified detail message.
Example :
An integer value “divide by zero” throw ArithmaticException.  In below example i am dividing int, double, float and long value with 0. For long and int type value it’s throwing Arithmatic Exception while for double and float printing special value as Infinity.  See below How to fix Arithmetic Exception? section.
package example;

public class ArithmaticExceptionExample {

	public static void main(String[] args) {
		int x=0;
		int y=5;
		double z=6;
		float l=6;
		long k=10L;
		//Integer value divide by integer value as 0 throw ArithmeticException
		try
		{
			System.out.println("Integer value divide by zero");
		System.out.println(y/x);
		}
		catch(ArithmeticException ex)
		{
			ex.printStackTrace();
		}
		//Double value divide by integer value as 0 No Exception special value Infinity
		System.out.println("Double value divide by zero");
		System.out.println(z/x);

		//Float value divide by integer value as 0 No Exception special value Infinity
		System.out.println("Float value divide by zero");
		System.out.println(l/x);

		//Long value divide by integer value as 0 throw ArithmeticException
		try
		{
		System.out.println("Long value divide by zero");
		System.out.println(k/x);
		}
		catch(ArithmeticException ex)
		{
			ex.printStackTrace();
		}

	}

}

Output:

Integer value divide by zero
java.lang.ArithmeticException: / by zero
	at example.ArithmaticExceptionExample.main(ArithmaticExceptionExample.java:15)
Double value divide by zero
Infinity
Float value divide by zero
Infinity
Long value divide by zero
java.lang.ArithmeticException: / by zero
	at example.ArithmaticExceptionExample.main(ArithmaticExceptionExample.java:31)

How to fix Arithmetic Exception?

In above example:

Y/X or K/X result ArithmeticException

What happens here is that since both the dividend and the divisor are int, the operation is an integer division, whose result is rounded to an int. Remember that an int can only contain whole number (of limited range, some 4 billion numbers approximately) That’ s why throwing Arithmatic Exception. same case for long value.

Z/X or L/X result special value Infinity

Here float (L) or double (X) precision value  divide by zero store in float and double value that why result is special value Infinity.

 

[Solved] JAVA java.lang.StringIndexOutOfBoundsException: String index out of range: -1 Example


The java.lang.StringIndexOutOfBoundsException is RuntimeException or Checked Exception which is thrown by the methods of String class during index operations which indicate accessing index is either negative or greater than size of string itself.

java.lang.StringIndexOutOfBoundException is subclass of the IndexOutOfBoundException class which is used to indicate that accessing index to either an  Array, Vector or String, is out of Range.

String Class Methods where StringIndexOutOfBoundsException happen:

String object index range is between 0 to String.length() -1 if object access beyond this range lower or greater will throw StringIndexOutOfBoundsException .

  • public char charAt(int index);
  • public String substring(beginIndex);
  • public String subString(beginIndex,endIndex);
  • public CharSequence subSequence(beginIndex,endIndex);
  • public static String valueOf(char[] data, int offset, int count)

Example : Below example is for print all possible SubString for String FacingIssuesOnIT will throw StringIndexOutOfBoundException. on run time because index conditions are not properly handled.

package example;

public class StringIndexOutOfBounExceptionExample {

	public static void main(String[] args) {
		String str = "FacingIssueOnIT";
		System.out.println("*********All Substring of FacingIssuesonIT");
		for (int i = 0; i <= str.length(); i++) {
			for (int j = i + 1; j <= str.length(); j++) {
				System.out.println(str.substring(i, j - i));
			}
		}
	}
}

Output :

*********All Substring of FacingIssuesonIT
F
Fa
Fac
Faci
Facin
Facing
FacingI
FacingIs
FacingIss
FacingIssu
FacingIssue
FacingIssueO
FacingIssueOn
FacingIssueOnI

a
ac
aci
acin
acing
acingI
acingIs
acingIss
acingIssu
acingIssue
acingIssueO
acingIssueOn
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
	at java.lang.String.substring(Unknown Source)
	at example.StringIndexOutOfBounExceptionExample.main(StringIndexOutOfBounExceptionExample.java:10)

Issues with above Example :
Actually, your right edge of your substring function may be lower than the left one. For example, when i=(size-1) and j=size, you are going to compute substring(size-1, 1). This is the cause of you error.

Modified Example:

When you compare with above example loop condition are change SubString above range selection is modified.

package example;

public class StringIndexOutOfBounExceptionExample {

	public static void main(String[] args) {
		String str = "FacingIssueOnIT";
		System.out.println("*********All Substring of FacingIssuesOnIT");
		for (int i = 0; i <=str.length()-1; i++) {
			for (int j = i+1 ; j <= str.length(); j++) {
				//System.out.println("i="+i+",j="+ j);
				System.out.println(str.substring(i, j));
			}
		}
	}
}

Output:

*********All Substring of FacingIssuesOnIT
F
Fa
Fac
Faci
Facin
Facing
FacingI
FacingIs
FacingIss
FacingIssu
FacingIssue
FacingIssueO
FacingIssueOn
FacingIssueOnI
FacingIssueOnIT
a
ac
aci
acin
acing
acingI
acingIs
acingIss
acingIssu
acingIssue
acingIssueO
acingIssueOn
acingIssueOnI
acingIssueOnIT
c
ci
cin
cing
cingI
cingIs
cingIss
cingIssu
cingIssue
cingIssueO
cingIssueOn
cingIssueOnI
cingIssueOnIT
i
in
ing
ingI
ingIs
ingIss
ingIssu
ingIssue
ingIssueO
ingIssueOn
ingIssueOnI
ingIssueOnIT
n
ng
ngI
ngIs
ngIss
ngIssu
ngIssue
ngIssueO
ngIssueOn
ngIssueOnI
ngIssueOnIT
g
gI
gIs
gIss
gIssu
gIssue
gIssueO
gIssueOn
gIssueOnI
gIssueOnIT
I
Is
Iss
Issu
Issue
IssueO
IssueOn
IssueOnI
IssueOnIT
s
ss
ssu
ssue
ssueO
ssueOn
ssueOnI
ssueOnIT
s
su
sue
sueO
sueOn
sueOnI
sueOnIT
u
ue
ueO
ueOn
ueOnI
ueOnIT
e
eO
eOn
eOnI
eOnIT
O
On
OnI
OnIT
n
nI
nIT
I
IT
T

How to avoid StringIndexOutOfBoundException?

  • Debug program throughly after printing index values.
  • During operation check index value range between 0 to String.length()-1.

[Solved] NullPointerException In Java


NullPointerException is Runtime Exception and Unchecked Exception which thrown when trying to access an object which is having value as null.

What is Null Value?

Null value is a special  value which tell JVM this reference variable is assigned with no value as null. It means variable is not pointing to any object instances and not having any value.

Cases when NullPointerException Happen:

  • Accessing or modifying a null object’s field.
  • Taking length of null  from object like String, Array, ArrayList etc.
  • Invoking a method from a null object.
  • Calling method passing argument as wrapper object having null value while method having primitive arguments.
  • Accessing or modifying the slots of null object, as if it were an array.
  • Throwing null, as if it were a Throwable value.
  • When you try to synchronize over a null object.

Below are some examples for NullPointerException for above cases which showing how NullPointerException can happen in your code.

import java.util.List;

public class NullPointerExceptionExample {

	public static void main(String[] args) {
		//Example 1: String object assigned with null
		try
		{
		String str=null;
		if(str.length()>0)//NullPointerException Here
			System.out.println("String Length :"+str.length());
		}
		catch(NullPointerException ex)
		{
			System.out.println("Example 1 :String object assigned with null");
			ex.printStackTrace();
		}

		//Example 2: Collection List Object Assigned with Null
		try
		{
		List list=null;
		if(list.size()>0)//NullPointerException Here
			System.out.println("List Length :"+list.size());
		}
		catch(NullPointerException ex)
		{
			System.out.println("Example2 :Collection List object assigned with null");
			ex.printStackTrace();
		}

		//Example 3: Calling method with wrapper and method having primitive value
		try
		{
		Long acNumber=null;
		checkValue(acNumber);
		}
		catch(NullPointerException ex)
		{
			System.out.println("Example 3 :Calling method with wrapper and method having primitive type");
			ex.printStackTrace();
		}

		//Example 4 :Accessing slot of Array object having value as null
		try
		{
		Employee [] empArr=new Employee[10];
		System.out.println("Employee Name :"+empArr[5].getName());
		}
		catch(NullPointerException ex)
		{
			System.out.println("Example 4: Accessing slot of array objet having value as null");
			ex.printStackTrace();
		}
	}

	public static void checkValue(long acNumber)
	{
		System.out.println("Account Number:"+acNumber);
	}

	private class Employee
	{
		private int id;
		private String name;
		private double salary;

		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public double getSalary() {
			return salary;
		}
		public void setSalary(double salary) {
			this.salary = salary;
		}

	}

}

Output :

Example 1 :String object assigned with null
java.lang.NullPointerException
	at example.NullPointerExceptionExample.main(NullPointerExceptionExample.java:12)
Example2 :Collection List object assigned with null
java.lang.NullPointerException
	at example.NullPointerExceptionExample.main(NullPointerExceptionExample.java:25)
Example 3 :Calling method with wrapper and method having primitive type
java.lang.NullPointerException
        at
example.NullPointerExceptionExample.main(NullPointerExceptionExample.java:38)
Example 4: Accessing slot of array objet having value as null
java.lang.NullPointerException
	at example.NullPointerExceptionExample.main(NullPointerExceptionExample.java:50)

 How to avoid NullPointerException?

NullPointerException can be avoid by using considering below points:

  • Need to ensure object as initialize properly before any operation check for null .
  • Need to ensure object reference is not null before calling any method or operation on fields.
  • While comparing string with literals. Instead of invoking the method from the null object, consider invoking it from the literal.
  • Before calling method check arguments if valid then only call methods.
  • Use of Ternary operator for initialize with some default value if object value is null.
  • We can use NullPointerException catch block when no action perform or if need to throw some Customize Exception or User Defined Exception.

In below example consider all above case for avoid NullPointerException.

public class NullPointerExceptionExample {

	public static void main(String[] args) {
		//Example 1: String object assigned with null
		//NullPointerException avoided by checking null before use
		String str=null;
		if(str!=null && str.length()>0)
			System.out.println("String Length :"+str.length());

		//Example 2: Object assigned with Null
		//NullPointerException avoided by using  null check before accessing field
		Employee emp=null;
		if(emp!=null)
			System.out.println("Employee Name :"+emp.getName());

		//Example 3: name is assigned with null
		//NullPointerException avoided by calling equals method from literals instead of name object.
		String name=null;
		if("FacingIssuesOnIT".equals(name))
		{
			System.out.println("Name is FacingIssuesOnIT");
		}
		else
		{
			System.out.println("Name is not FacingIssuesOnIT");
		}

		//Example 4: Calling method with wrapper as null and method having primitive value
		//NullPointerException avoided by checking null on method arguments before calling method.

		Long acNumber=null;
		if(acNumber!=null)
		{
		checkValue(acNumber);
		}

		//Example 5: Object reference value is null and need to perform operation
		//NullPointerException avoided by using ternary operator
		String siteName=null;
		name=siteName==null?"":siteName;
		System.out.println("Site Name Length:"+name.length() );

	}

	public static void checkValue(long acNumber)
	{
		System.out.println("Account Number:"+acNumber);
	}

	private class Employee
	{
		private int id;
		private String name;
		private double salary;

		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public double getSalary() {
			return salary;
		}
		public void setSalary(double salary) {
			this.salary = salary;
		}

	}

}

Summary

  • Here you have learn about NullPointerException and Null value.
  • Cases with examples where NullPointerException can happen.
  • Al so explained with example to avoid NullPointerException by applying null check on object, compare String values by calling operations on literals and using ternary operators.