Tag Archives: java.lang.IllegalArgumentException

[Solved] Date Format : java.lang.IllegalArgumentException: Illegal pattern character ‘Z’ or ‘T’


SimpleDateFormat throw java.lang.IllegalArgumentException at runtime while parsing date format.

Follow link below to get in depth knowledge of IllegalArgumentException .

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

Example DateTime throwing IllegalArgumentexception

In this example target format is throwing IllegalArgumentException because of using illegal pattern character as Z and T.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeDateFormat {

	public static void main(String[] args) {
		String targetFormat = "MM/DD/YYYY hh:mm:ss a";
		String currentFormat = "yyyy-MM-ddThh:mm:ss.SSSZ";
		String sourceDate = "2019-02-12T11:29:10.761Z";
		System.out.println("Source Date :"+sourceDate);
		String timezone = "CDT";
		DateFormat srcDf = new SimpleDateFormat(currentFormat);
		srcDf.setTimeZone(TimeZone.getTimeZone(timezone));
		DateFormat destDf = new SimpleDateFormat(targetFormat);
		try {
			Date date = srcDf.parse(sourceDate);
			String targetDate = destDf.format(date);
			System.out.println("Target Date :"+targetDate);

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

	}

}

Output :


Source Date :2019-02-12T11:29:10.761Z
Exception in thread "main" java.lang.IllegalArgumentException: Illegal pattern character 'T'
    at java.text.SimpleDateFormat.compile(Unknown Source)
    at java.text.SimpleDateFormat.initialize(Unknown Source)
    at java.text.SimpleDateFormat.(Unknown Source)
    at java.text.SimpleDateFormat.(Unknown Source)
    at com.fiot.test.ChangeDateFormat.main(ChangeDateFormat.java:17)

Solutions

SimpleDateFormat allow only some key characters only while using date time formatting. Here using characters Z and T for matching date time pattern in sourceDate that what throwing IllegalArgumentException . To resolve such issues for using  characters apart from formatting char in date format always use with ‘Z’ or ‘T’ (with single quote) as given below. Follow link to see complete list for formatting characters and date format.

Date Time Formatting Characters and Patterns

Correct Date Time Format
"yyyy-MM-dd'T'hh:mm:ss.SSS'Z'"

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeDateFormat {

	public static void main(String[] args) {
		String targetFormat = "MM/DD/YYYY hh:mm:ss a";
		String currentFormat = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";
		String sourceDate = "2019-02-12T11:29:10.761Z";
		System.out.println("Source Date :"+sourceDate);
		String timezone = "CDT";
		DateFormat srcDf = new SimpleDateFormat(currentFormat);
		srcDf.setTimeZone(TimeZone.getTimeZone(timezone));
		DateFormat destDf = new SimpleDateFormat(targetFormat);
		try {
			Date date = srcDf.parse(sourceDate);
			String targetDate = destDf.format(date);
			System.out.println("Target Date :"+targetDate);

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

	}

}

Output:


Source Date :2019-02-12T11:29:10.761Z
Target Date :02/43/2019 04:59:10 PM

More Issues Solution

To solved Date Time same code , formatting  and issues solutions follow the link given below:

Java Date and Time Handling Tutorial

 

Advertisements

[Solved] Date Format AM/PM : java.lang.IllegalArgumentException: Illegal pattern character ‘A’


SimpleDateFormat throw java.lang.IllegalArgumentException at runtime while parsing date format.

Follow link below to get in depth knowledge of IllegalArgumentException .

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

Example DateTime throwing IllegalArgumentexception

In this example target format is throwing IllegalArgumentException because of using invalid formatting char for display AM/PM.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeDateFormat {

	public static void main(String[] args) {
		String targetFormat = "MM/DD/YYYY hh:mm:ss AM/PM";
		String currentFormat = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";
		String sourceDate = "2019-02-12T11:29:10.761Z";
		System.out.println("Source Date :"+sourceDate);
		String timezone = "CDT";
		DateFormat srcDf = new SimpleDateFormat(currentFormat);
		srcDf.setTimeZone(TimeZone.getTimeZone(timezone));
		DateFormat destDf = new SimpleDateFormat(targetFormat);
		try {
			Date date = srcDf.parse(sourceDate);
			String targetDate = destDf.format(date);
			System.out.println("Target Date :"+targetDate);

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

	}

}

Output:


Source Date :2019-02-12T11:29:10.761Z
Exception in thread "main" java.lang.IllegalArgumentException: Illegal pattern character 'A'
    at java.text.SimpleDateFormat.compile(Unknown Source)
    at java.text.SimpleDateFormat.initialize(Unknown Source)
    at java.text.SimpleDateFormat.(Unknown Source)
    at java.text.SimpleDateFormat.(Unknown Source)
    at com.fiot.test.ChangeDateFormat.main(ChangeDateFormat.java:19)

Solutions :

SimpleDateFormat allow only some key characters only while using date time formatting. Here for showing AM/PM should use character as as mentioned in below code in targetFormat. Follow link to see complete list for formatting characters and date format.

Date Time Formatting Characters and Patterns

Correct format to AM/PM
"MM/DD/YYYY hh:mm:ss a"

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeDateFormat {

	public static void main(String[] args) {
		String targetFormat = "MM/DD/YYYY hh:mm:ss a";
		String currentFormat = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";
		String sourceDate = "2019-02-12T11:29:10.761Z";
		System.out.println("Source Date :"+sourceDate);
		String timezone = "CDT";
		DateFormat srcDf = new SimpleDateFormat(currentFormat);
		srcDf.setTimeZone(TimeZone.getTimeZone(timezone));
		DateFormat destDf = new SimpleDateFormat(targetFormat);
		try {
			Date date = srcDf.parse(sourceDate);
			String targetDate = destDf.format(date);
			System.out.println("Target Date :"+targetDate);

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

	}

}

Output:


Source Date :2019-02-12T11:29:10.761Z
Target Date :02/43/2019 04:59:10 PM

More Issues Solution

To solved Date Time same code , formatting  and issues solutions follow the link given below:

Java Date and Time Handling Tutorial

[Solved] java.lang.IllegalArgumentException: No enum constant


Pre-requisite :  Java : Enumeration Handling

Below is example of enumeration by using all implicit methods of enumeration.
Here used wrong value of enumeration as “Saturday” while using month name here that’s why causing this issue.

package enm;

public class EnumTest {

	enum Month{JANNUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER};
	enum MonthDetail{
		JANNUARY("January",1),
		FEBRUARY("February",2),
		MARCH("March",3),
		APRIL("April",4),
		MAY("May",5),
		JUNE("June",6),
		JULY("July",7),
		AUGUST("August",8),
		SEPTEMBER("September",9),
		OCTOBER("October",10),
		NOVEMBER("November",11),
		DECEMBER("December",12);

		public String monthName="";
		public int index;

		//Constructor will always private
		private MonthDetail(String monthName,int index)
		{
			this.monthName=monthName;
			this.index=index;
		}
		//Method
		public void showMonthDetail()
		{
			System.out.println(this.index +" : "+this.monthName);
		}
	};
	public static void main(String[] args) {
		for(Month month:Month.values())
		{
	    //Add one because by default enum indexing start from 0
		System.out.println((month.ordinal()+1) +" : "+month.name());
		}
		//Every enum Class provide values method to get list of enums
		for(MonthDetail monthDetail:MonthDetail.values())
		{
			monthDetail.showMonthDetail();
		}

		try
		{
		MonthDetail mnth=MonthDetail.valueOf("Saturday");
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

Output


1 : JANNUARY
2 : FEBRUARY
3 : MARCH
4 : APRIL
5 : MAY
6 : JUNE
7 : JULY
8 : AUGUST
9 : SEPTEMBER
10 : OCTOBER
11 : NOVEMBER
12 : DECEMBER
1 : January
2 : February
3 : March
4 : April
5 : May
6 : June
7 : July
8 : August
9 : September
10 : October
11 : November
12 : December
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant enm.EnumTest.MonthDetail.Saturday
    at java.lang.Enum.valueOf(Enum.java:238)
    at enm.EnumTest$MonthDetail.valueOf(EnumTest.java:1)
    at enm.EnumTest.main(EnumTest.java:49)

Solutions:
Always use valid constant values to resolve this issue and while trying to call this enum.valueOf() method always handle exception so that any exception happen then your program will not terminate.

try {
 MonthDetail mnth=MonthDetail.valueOf("August");
} catch(Exception ex) {
ex.printStackTrace();
}

To learn more on Enumeration follow below link: Java : Enumeration Handling

 

[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