English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

When to throw IllegalStateException and IllegalArgumentException? In Java?

IllegalStateException:

An exception will be generated and an IlleagalStateException will be created when you call the method at an illegal or inappropriate time.

For example,remove()is called on the ArrayList class methodnext()Delete the last element after the method or before.

  • After deleting the element at the current position, you need to move to the next element to delete it, that is, each time you call thisnext()When calling thisremove()method once.

  • Since the initial position of the list (pointer) will be before the first element, this method cannot be called without calling the next method.

If calling thisremove()method, otherwise it will throw java.lang.IllegalStateException.

Example

In the following example, we try to useremove()The method removes an element from the ArrayList and then moves to the first element

import java.util.ArrayList;
import java.util.ListIterator;
public class NextElementExample{
   public static void main(String args[]) {
      //Instantiate an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      //Fill the ArrayList-
      list.add("apples");
      list.add("mangoes");
      //Get the Iterator object of ArrayList
      ListIterator<String> it = list.listIterator();
      //Remove an element without moving to the 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-IllegalArgumentException will be thrown whenever inappropriate parameters are passed to a method or constructor.

Example

valueOf()The methods of the java.sql.Date class accept a String in JDBC escape format yyyy- [m] m- [d] d represents a date String and converts it to a java.sql.Date object. However, if the date String is passed in any other format, this method will throw 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)