Category Archives: Error

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

Advertisements

[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

[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] Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \’  \”;  \\ )


“Invalid escape sequence” is most common error at compile time while using Regular Exception or defining File Path while file handling for reading and writing files.

As per JAVA only valid sequence characters are (\b, \t, \n, \f, \r, \”, \’, \). In your code if you are using \ with another character instead of above valid sequence characters then JAVA will throw Compile time error as “Invalid Sequence Characters

Here after showing below Regular Expression and File Path example for throwing will explain about the solution of this.

Regular Expression Example :


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 is a site to help others by sharing others experience";
		Pattern pattern = Pattern.compile("\w");
		System.out.println("Saurabh");
		Matcher matcher = pattern.matcher(text);
		if (matcher != null &amp;&amp; matcher.find()) {
			for (int i = 0; i<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span><span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span><span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>&lt;matcher.groupCount(); i++) {
				System.out.println(matcher.group(i));
			}
		}
	}
}

Output :

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )

at com.test.exceptions.RegularExpressionTest.main(RegularExpressionTest.java:10)

File Path Example:

package com.test.exceptions;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class FilePathTest {

	public static void main(String[] args) {
		try
		{
		BufferedReader job = new BufferedReader
	               (new FileReader("F:\\Elasticsearch\FacingIssuesOnIT.txt"));
		}
		catch(FileNotFoundException ex)
		{
			ex.printStackTrace();
		}

	}

}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
	Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \"  \'  \\ )

	at com.test.exceptions.FilePathTest.main(FilePathTest.java:13)

  1. Replace all \ with \\ if using with any other place  instead of valid sequence characters are (\b, \t, \n, \f, \r, \”, \’, \\).
  2. If using eclipse, there is option for setting to automatically add escape chars when pasting text:

Windows -> Preferences ->Java ->Editor -> Typing -> In String Literals ->Escape text when pasting into String literals.

For Example : For above case will change like below

Copy Text :

\w

F:\Elasticsearch\FacingIssuesOnIT.txt

Paste Text :

\w

F:\Elasticsearch\FacingIssuesOnIT.txt

Please below steps for Eclipse Setting for Escape Characters String Literals.

Eclipse Setting for Escape Characters String
Eclipse Setting for Escape Characters String

Summary :

  • Explained cases of exception “Unresolved compilation problem:
    Invalid escape sequence (valid ones are \b \t \n \f \r \” \’ \\ )”
  • Detailed example of Regular Expression and File Path for Invalid escape sequence.
  • Provide Manual solution to fix this compile time issue “Invalid escape sequence”
  • Provide steps to setting escape characters for invalid sequence characters.

[Solved] Invalid escape sequence (valid ones are  b  t  n  f  r  ‘  “;  \ )


“Invalid escape sequence” is most common error at compile time while using Regular Exception or defining File Path while file handling for reading and writing files.

As per JAVA only valid sequence characters are (b, t, n, f, r, “, ‘, \). In your code if you are using with another character instead of above valid sequence characters then JAVA will throw Compile time error as “Invalid Sequence Characters

Here after showing below Regular Expression and File Path example for throwing will explain about the solution of this.

Regular Expression Example :


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 is a site to help others by sharing others experience";
		Pattern pattern = Pattern.compile("w");
		System.out.println("Saurabh");
		Matcher matcher = pattern.matcher(text);
		if (matcher != null &amp;&amp; matcher.find()) {
			for (int i = 0; i<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span><span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span><span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>&lt;matcher.groupCount(); i++) {
				System.out.println(matcher.group(i));
			}
		}
	}
}

Output :

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Invalid escape sequence (valid ones are b t n f r " ' \ )

at com.test.exceptions.RegularExpressionTest.main(RegularExpressionTest.java:10)

File Path Example:

package com.test.exceptions;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class FilePathTest {

	public static void main(String[] args) {
		try
		{
		BufferedReader job = new BufferedReader
	               (new FileReader("F:\ElasticsearchFacingIssuesOnIT.txt"));
		}
		catch(FileNotFoundException ex)
		{
			ex.printStackTrace();
		}

	}

}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
	Invalid escape sequence (valid ones are  b  t  n  f  r  "  '  \ )

	at com.test.exceptions.FilePathTest.main(FilePathTest.java:13)

  1. Replace all with \ if using with any other place  instead of valid sequence characters are (b, t, n, f, r, “, ‘, \).
  2. If using eclipse, there is option for setting to automatically add escape chars when pasting text:

Windows -> Preferences ->Java ->Editor -> Typing -> In String Literals ->Escape text when pasting into String literals.

For Example : For above case will change like below

Copy Text :

w

F:\ElasticsearchFacingIssuesOnIT.txt

Paste Text :

\w

F:\Elasticsearch\FacingIssuesOnIT.txt

Please below steps for Eclipse Setting for Escape Characters String Literals.

Eclipse Setting for Escape Characters String
Eclipse Setting for Escape Characters String

Summary :

  • Explained cases of exception “Unresolved compilation problem:
    Invalid escape sequence (valid ones are b t n f r ” ‘ \ )”
  • Detailed example of Regular Expression and File Path for Invalid escape sequence.
  • Provide Manual solution to fix this compile time issue “Invalid escape sequence”
  • Provide steps to setting escape characters for invalid sequence characters.