When do IllegalStateException and IllegalArgumentException get thrown? in java?

Java 8Object Oriented ProgrammingProgramming

IllegalStateException:

This exception is thrown when you call a method at illegal or inappropriate time an IlleagalStateException is generated.

For example, the remove() method of the ArrayList class removes the last element after calling the next() or previous methods.

  • After removing the element at the current position you need to move to the next element to remove it i.e. per one call of the next() method you can invoke this remove() method only once.
  • Since the initial position of the list (pointer) will be before the first element, you cannot invoke this method without calling the next method.

If you invoke the remove() method otherwise it throws an java.lang.IllegalStateException.

Example

In the following example we are trying to remove an element of the ArrayList using the remove() method, before moving to 1st element

import java.util.ArrayList;
import java.util.ListIterator;
public class NextElementExample{
   public static void main(String args[]) {
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      //populating the ArrayList
      list.add("apples");
      list.add("mangoes");
      //Getting the Iterator object of the ArrayList
      ListIterator<String> it = list.listIterator();
      //Removing the element without moving to first position
      it.remove();
   }
}

Runtime exception

Exception in thread "main" java.lang.IllegalStateException
   at java.util.ArrayList$Itr.remove(Unknown Source)
   at MyPackage.NextElementExample.main(NextElementExample.java:17)

IllegalArgumentException − Whenever you pass inappropriate arguments to a method or constructor, an IllegalArgumentException is thrown.

Example

The valueOf() method of the java.sql.Date class accepts a String representing a date in JDBC escape format yyyy-[m]m-[d]d and converts it into a java.sql.Date object. But, if you pass date String in any other format this method throws an IllegalArgumentException.

import java.sql.Date;
import java.util.Scanner;
public class IllegalArgumentExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your date of birth in JDBC escape format (yyyy-mm-dd) ");
      String dateString = sc.next();
      Date date = Date.valueOf(dateString);
      System.out.println("Given date converted int to an object: "+date);
   }
}

Runtime exception

Enter your date of birth in JDBC escape format (yyyy-mm-dd)
26-07-1989
Exception in thread "main" java.lang.IllegalArgumentException
   at java.sql.Date.valueOf(Unknown Source)
   at july_ipoindi.NextElementExample.main(NextElementExample.java:11)
raja
Published on 06-Aug-2019 14:41:11
Advertisements