Category Archives: Exception

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

Advertisements

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