Java : IllegalArgumentException with Examples
IllegalArgumentException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most IllegalArgumentException methods.
Summary
public void func(String str) {
if (str == null) {
throw new IllegalArgumentException("str is null!");
}
if (str.isEmpty()) {
throw new IllegalArgumentException("str is empty!");
}
System.out.println(str);
}
func("abcd"); // abcd
func(null); // java.lang.IllegalArgumentException: str is null!
func(""); // java.lang.IllegalArgumentException: str is empty!
If you only check for null or not, it is recommended to use the Objects.requireNonNull method instead.
public void func(String str) {
Objects.requireNonNull(str, "str is null!");
System.out.println(str);
}
func("abcd"); // abcd
func(null); // java.lang.NullPointerException: str is null!
Constructors
IllegalArgumentException ()
final var e = new IllegalArgumentException();
System.out.println(e); // java.lang.IllegalArgumentException
IllegalArgumentException (String s)
final var e = new IllegalArgumentException("abcde");
System.out.println(e); // java.lang.IllegalArgumentException: abcde
System.out.println(e.getMessage()); // abcde
IllegalArgumentException (String message, Throwable cause)
final var cause = new IllegalArgumentException("XYZ");
final var e = new IllegalArgumentException("abcde", cause);
System.out.println(e); // java.lang.IllegalArgumentException: abcde
System.out.println(e.getMessage()); // abcde
System.out.println(e.getCause()); // java.lang.IllegalArgumentException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ
IllegalArgumentException (Throwable cause)
final var cause = new IllegalArgumentException("XYZ");
final var e = new IllegalArgumentException(cause);
System.out.println(e); // java.lang.IllegalArgumentException: java.lang.IllegalArgumentException: XYZ
System.out.println(e.getMessage()); // java.lang.IllegalArgumentException: XYZ
System.out.println(e.getCause()); // java.lang.IllegalArgumentException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ
Methods declared in Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Please see the link below.
Related posts
- API Examples
- Error
- Exception
- RuntimeException
- ArithmeticException
- ArrayIndexOutOfBoundsException
- ArrayStoreException
- CancellationException
- ClassCastException
- ConcurrentModificationException
- DateTimeException
- DateTimeParseException
- IllegalStateException
- IndexOutOfBoundsException
- NoSuchElementException
- NullPointerException
- PatternSyntaxException
- StringIndexOutOfBoundsException
- UnsupportedOperationException
- Throwable