IllegalArgumentException in Java example10 Sept 2024 | 3 min read Java, a widely used programming language, is known for its robustness and protection capabilities. However, even in the maximum cautiously crafted programs, mistakes can occur. One common type of error is the "Illegal Argument Exception." In this section, we are going to explore what this exception is, why it occurs, and offer examples with full programs to illustrate its behaviour. What is Illegal Argument Exception?In Java, an IllegalArgumentException is a runtime exception that takes place whilst a method is known as with an argument this is illegal or inappropriate. It means that the argument does no longer meet the approach's expectancies or violates its preconditions. InvalidArgumentExceptionExample.java Output: Exception in thread "main" java.lang.IllegalArgumentException: Name cannot be null at InvalidArgumentExceptionExample.addName(InvalidArgumentExceptionExample.java:12) at InvalidArgumentExceptionExample.main(InvalidArgumentExceptionExample.java:8) We create an easy program that continues a list of names. The addName() method is designed to feature a name to the listing, but it assessments if the furnished name is null. If the name is null, an IllegalArgumentException is thrown with a descriptive error message. In this situation, the program attempts to feature a null call to the list, triggering the IllegalArgumentException due to the fact the technique explicitly forbids null names. Let's explore common eventualities where IllegalArgumentException may occur: 1. Null Arguments:NullArgumentExceptionExample.java Output: Exception in thread "main" java.lang.IllegalArgumentException: Text cannot be null at NullArgumentExceptionExample.printLength(NullArgumentExceptionExample.java:10) at NullArgumentExceptionExample.main(NullArgumentExceptionExample.java:6) The printLength() method expects a non-null string, and if null is provided, an IllegalArgumentException is thrown. Invalid Numeric Values:InvalidNumberArgumentExceptionExample.java Output: Exception in thread "main" java.lang.IllegalArgumentException: Number must be non-negative at InvalidNumberArgumentExceptionExample.calculateSquareRoot(InvalidNumberArgumentExceptionExample.java:10) at InvalidNumberArgumentExceptionExample.main(InvalidNumberArgumentExceptionExample.java:6) The calculateSquareRoot technique calculates the square root of quite a number however only accepts non-negative values. If a poor quantity is supplied, an IllegalArgumentException is thrown. 2. Empty or Invalid Collections:InvalidCollectionArgumentExceptionExample.java Output: Exception in thread "main" java.lang.IllegalArgumentException: List must be non-null and non-empty at InvalidCollectionArgumentExceptionExample.processList(InvalidCollectionArgumentExceptionExample.java:11) at InvalidCollectionArgumentExceptionExample.main(InvalidCollectionArgumentExceptionExample.java:6) The processList() technique expects a non-null and non-empty listing. If a null or empty list is supplied, an IllegalArgumentException is thrown. Best Practices to Handle IllegalArgumentExceptionTo manage IllegalArgumentException gracefully, bear in mind the following first-rate practices:
In Summary, understanding and handling IllegalArgumentException is critical for writing sturdy and reliable Java programs. By validating inputs, offering descriptive blunders messages, and following pleasant practices, builders can create code that isn't most effective purposeful but also resilient to unexpected inputs. As illustrated within the examples, catching and addressing unlawful arguments early in the development system contributes to the general balance and maintainability of Java applications. Next TopicIs the main() method compulsory in Java |
The Factory Method Design Pattern, as a creational pattern in object-oriented programming, provides an interface for creating the object but leaves the decision as to what class should be instantiated in the concrete subclasses. It is the pattern of loose coupling since the application will not be...
7 min read
Given an integer array (arr) and an integer target, we need to find the value closest to the target that can be obtained by applying the bitwise AND operation on a non-empty subarray of arr. The task is to return the minimum absolute difference between the...
8 min read
In the world of programming, one of the fundamental exercises that help develop logical thinking and problem-solving skills is the creation of various patterns using loops. Patterns not only make coding fun but also improve our understanding of how loops and conditions work in programming...
4 min read
Statements are roughly equivalent to sentences in natural languages. In general, statements are just like English sentences that make valid sense. In this section, we will discuss what is a statement in Java and the types of statements in Java. What is statement in Java? In Java, a...
2 min read
In this section, we will learn what is a partition number and also create Java programs to check if the given number is a partition number or not. The partition number program is frequently asked in Java coding interviews and academics. Partition Number In combinatorics and number theory,...
4 min read
is one of the unchecked exceptions that occur when we try to convert one class type object into another class type. ClassCast Exception is thrown when we try to cast an object of the parent class to the child class object. However, it can also be...
1 min read
In this section, we will learn what is a Catalan number and also create Java programs to check if the given number is a Catalan number or not. The Catalan number program is frequently asked in Java coding interviews and academics. There are many interesting problems that...
6 min read
In the realm of database programming, handling large text data is a common requirement. Java, being one of the most widely used programming languages, provides various mechanisms to interact with databases. One such mechanism is the (Character Large Object), which is designed specifically to manage...
5 min read
A magic square is a square matrix (an (n times n) grid) of unique positive integers organized in such a way that the total of the numbers in each row, column, and both main diagonals is equal. This constant sum is known as the magical constant....
7 min read
? Numerous tasks involve counting dates, such as scheduling events and figuring out how many days there are between two dates. The built-in Date and Calendar classes in Java make it simpler to work with dates and let you carry out a number of actions on them,...
4 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India