List of Unchecked Exceptions in Java
Java is a popular programming language that is widely used for developing a wide range of applications, including desktop, web, and mobile applications. One of the key features of Java is its exception handling mechanism, which allows developers to handle errors and exceptions in a structured and systematic way.
In Java, there are two types of exceptions: checked exceptions and unchecked exceptions. Checked exceptions are exceptions that are checked at compile-time, which means that the compiler will ensure that the code that might throw a checked exception is properly handled. Unchecked exceptions, on the other hand, are exceptions that are not checked at compile-time, which means that the compiler does not require the code to handle them explicitly.
Unchecked exceptions are also known as runtime exceptions because they occur during runtime and can lead to the termination of the program if they are not handled properly. In this article, we will discuss some of the common unchecked exceptions in Java.
1. NullPointerException
NullPointerException is one of the most common unchecked exceptions in Java. It occurs when a null reference is used in a method that requires a non-null reference. For example, if you try to call a method on an object that is null, you will get a NullPointerException.
Example:
public class Example {
public static void main(String[] args) {
String str = null;
int length = str.length(); // This line will throw a NullPointerException
System.out.println(length);
}
}
This code declares a String variable str and initializes it to null. The next line tries to call the length() method on str, which is not possible because str is null. This will result in a NullPointerException being thrown.
2. ArrayIndexOutOfBoundsException:
ArrayIndexOutOfBoundsException is another common unchecked exception in Java. It occurs when you try to access an element of an array with an index that is out of range. For example, if you try to access the 10th element of an array with only 9 elements, you will get an ArrayIndexOutOfBoundsException. Here's an example code snippet that could throw an ArrayIndexOutOfBoundsException:
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // trying to access the 4th element of the array, which doesn't exist
In this code, we have an array of integers with three elements. However, when we try to access the fourth element (which doesn't exist), we'll get an ArrayIndexOutOfBoundsException.
3. IllegalArgumentException:
IllegalArgumentException is an unchecked exception that occurs when a method is called with an illegal or inappropriate argument. For example, if you pass a negative value to a method that expects a positive value, you will get an IllegalArgumentException. Here's a code snippet that could throw an IllegalArgumentException:
public void divide(int numerator, int denominator) {
if (denominator == 0) {
throw new IllegalArgumentException("Denominator cannot be zero.");
}
int result = numerator / denominator;
System.out.println(result);
}
In this code, we have a method called divide that takes two integer parameters: numerator and denominator. If the denominator is zero, we throw an IllegalArgumentException with a message explaining that the denominator cannot be zero. If the denominator is not zero, we perform the division and print the result. If the denominator is zero, an IllegalArgumentException will be thrown with the message we provided.
4. ClassCastException:
ClassCastException is an unchecked exception that occurs when you try to cast an object to a class that it is not compatible with. For example, if you try to cast an object of type String to an object of type Integer, you will get a ClassCastException. Here's an example code snippet that could throw a ClassCastException:
Object number = 10;
String str = (String) number; // trying to cast an Integer object to a String
In this code, we have an Object variable called number that is assigned an Integer object with a value of 10. However, when we try to cast the Integer object to a String using the (String) cast operator, we'll get a ClassCastException because Integer objects cannot be cast to String objects.
5. ArithmeticException:
ArithmeticException is an unchecked exception that occurs when an arithmetic operation fails. For example, if you divide a number by zero, you will get an ArithmeticException. here's an example code snippet that could throw an ArithmeticException:
int a = 10;
int b = 0;
int c = a / b; // trying to divide by zero
In this code, we have two integer variables, a and b. We're trying to divide a by b to calculate the value of c. However, since b is set to 0, this will result in a division by zero, which is not allowed in Java. When we run this code, we'll get an ArithmeticException.
6. UnsupportedOperationException:
UnsupportedOperationException is an unchecked exception that occurs when an operation is not supported. For example, if you try to add an element to an immutable list, you will get an UnsupportedOperationException. Here's an example code snippet that could throw an UnsupportedOperationException:
List<String> fruits = Arrays.asList("apple", "banana", "orange");
fruits.add("grape"); // trying to add an element to an unmodifiable list
In this code, we have a List of strings called fruits, which is created using the Arrays.asList method. This creates an unmodifiable list, which means that we cannot add or remove elements from it. However, when we try to add an element to the fruits list using the add method, we'll get an UnsupportedOperationException because the list is unmodifiable.
7. IllegalStateException:
IllegalStateException is an unchecked exception that occurs when the state of an object is not in the expected state to perform an operation. For example, if you try to call a method on a closed resource, you will get an IllegalStateException. Here's an example code snippet that could throw an IllegalStateException:
public class Car {
private boolean engineOn;
public void turnOnEngine() {
if (engineOn) {
throw new IllegalStateException("Engine is already on.");
}
engineOn = true;
System.out.println("Engine is now on.");
}
}
In this code, we have a Car class with a private boolean variable engineOn that represents whether the car's engine is turned on or not. We have a method turnOnEngine that tries to turn on the engine. However, if the engine is already on (engineOn is true), we throw an IllegalStateException with a message saying that the engine is already on. If the engine is not on, we set engineOn to true and print a message indicating that the engine is now on. If turnOnEngine is called when the engine is already on, an IllegalStateException will be thrown with the message we provided.
8. NumberFormatException:
NumberFormatException is an unchecked exception that occurs when you try to convert a string to a numeric type, but the string is not in the correct format. For example, if you try to convert the string "abc" to an integer, you will get a NumberFormatException. Here's an example code snippet that could throw a NumberFormatException:
String numberString = "abc";
int number = Integer.parseInt(numberString); // trying to convert a non-numeric string to an integer
In this code, we have a String variable numberString that is assigned a non-numeric string value "abc". We're then trying to convert this string to an integer using the Integer.parseInt() method. Since "abc" cannot be parsed as an integer, this will result in a NumberFormatException.
9. AssertionError:
AssertionError is an unchecked exception that occurs when an assertion fails. Assertions are used to verify that certain conditions are true at runtime, and if an assertion fails, an AssertionError is thrown. Here's an example code snippet that could throw an AssertionError:
int age = 15;
assert age >= 18 : "Person must be 18 or older."; // asserting that the person's age is at least 18
In this code, we have an integer variable age that is assigned a value of 15. We're then using an assertion to check that the age is at least 18. Since 15 is not greater than or equal to 18, this will trigger an AssertionError with the message "Person must be 18 or older.". Note that assertions must be enabled in order for this code to have any effect.
10. SecurityException:
SecurityException is an unchecked exception that occurs when a security violation occurs. For example, if you try to access a protected resource without proper permissions, you will get a SecurityException. Here's an example code snippet for the SecurityException:
try {
// Some code that may throw a SecurityException
} catch (SecurityException e) {
// Handle the exception
e.printStackTrace();
}
In this code snippet, we are using a try-catch block to handle a SecurityException. The code inside the try block may throw a SecurityException, which is a type of checked exception that is thrown.
11. OutOfMemoryError:
OutOfMemoryError is an unchecked error that occurs when the Java Virtual Machine (JVM) runs out of memory. This can happen when an application allocates too much memory or when there is not enough memory available on the system. Here's an example code snippet that could potentially trigger an OutOfMemoryError:
public class OutOfMemoryExample {
public static void main(String[] args) {
// create an ArrayList to hold a large number of objects
ArrayList<Object> list = new ArrayList<Object>();
while (true) {
// add objects to the list
list.add(new Object());
}
}
}
In this example, the main method creates an ArrayList and enters an infinite loop where it adds new Object instances to the list. Eventually, the list will consume all available memory, causing the JVM to throw an OutOfMemoryError.
12. StackOverflowError:
StackOverflowError is an unchecked error that occurs when the call stack overflows. This can happen when a method calls itself recursively too many times, causing the call stack to grow too large. Here's an example code snippet that could potentially trigger a StackOverflowError:
public class StackOverflowExample {
public static void main(String[] args) {
recursiveMethod(0);
}
public static void recursiveMethod(int i) {
System.out.println(i);
recursiveMethod(i + 1);
}
}
In this example, the main method calls the recursiveMethod method with an initial value of 0. The recursiveMethod method prints the current value of i and then calls itself with an incremented value of i. This process repeats until the JVM's call stack is full, at which point a StackOverflowError will be thrown.
13. ConcurrentModificationException:
ConcurrentModificationException is an unchecked exception that occurs when an object is modified concurrently by multiple threads. For example, if you try to modify a collection while another thread is iterating over it, you will get a ConcurrentModificationException. Here's an example code snippet that could potentially trigger a ConcurrentModificationException:
public class ConcurrentModificationExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
list.add("orange");
for (String fruit : list) {
if (fruit.equals("banana")) {
list.remove(fruit); // attempting to modify the list while iterating over it
}
}
}
}
In this example, the main method creates an ArrayList and adds three String values to it. It then attempts to remove the "banana" element from the list while iterating over it using a for-each loop. This modification of the list while iterating over it causes a ConcurrentModificationException to be thrown.
14. EmptyStackException:
EmptyStackException is an unchecked exception that occurs when you try to pop an element from an empty stack. This can happen when you pop more elements than you push, or if you pop an element from an empty stack. here's a code snippet that could potentially result in an EmptyStackException:
Stack<Integer> myStack = new Stack<>();
myStack.pop(); // attempting to pop an element from an empty stack
In this example, we create a new Stack instance called myStack. However, we immediately try to pop an element from it using the pop() method. Since myStack is empty at this point, attempting to pop an element from it will result in an EmptyStackException.
15. NoSuchElementException:
NoSuchElementException is an unchecked exception that occurs when you try to access an element from an empty collection or iterator. For example, if you try to get the next element from an empty iterator, you will get a NoSuchElementException. Here's a code snippet that could potentially result in a NoSuchElementException:
List<Integer> myList = Arrays.asList(1, 2, 3);
Iterator<Integer> myIterator = myList.iterator();
myIterator.next(); // returns 1
myIterator.next(); // returns 2
myIterator.next(); // returns 3
myIterator.next(); // throws NoSuchElementException
In this example, we create a new List called myList containing the elements 1, 2, and 3. We then create a new iterator called myIterator using the iterator() method of myList. We call myIterator.next() three times, which returns the first three elements of myList (1, 2, and 3). However, when we call myIterator.next() a fourth time, there are no more elements left to return, so a NoSuchElementException is thrown.
16. NegativeArraySizeException:
NegativeArraySizeException is an unchecked exception that occurs when you try to create an array with a negative size. For example, if you try to create an array with -1 size, you will get a NegativeArraySizeException. Here's a code snippet that could potentially result in a NegativeArraySizeException:
int[] myArray = new int[-5]; // attempting to create an array with negative length
In this example, we're trying to create a new array of integers called myArray, but we're attempting to give it a negative length (-5). This is not allowed, as arrays in Java must have a non-negative length. Attempting to create an array with a negative length will result in a NegativeArraySizeException.
17. EnumConstantNotPresentException:
EnumConstantNotPresentException is an unchecked exception that occurs when an invalid enumeration value is used. For example, if you try to use an enumeration value that does not exist, you will get an EnumConstantNotPresentException. Here's a code snippet that could potentially result in an EnumConstantNotPresentException:
enum MyEnum {
VALUE1,
VALUE2,
VALUE3
}
MyEnum myEnum = MyEnum.valueOf("VALUE4"); // attempting to get an enum constant that doesn't exist
In this example, we define an enumeration called MyEnum with three possible values: VALUE1, VALUE2, and VALUE3. We then attempt to retrieve an enum constant using the valueOf() method and passing in a string that does not match any of the values in the enumeration.Attempting to get an enum constant that doesn't exist will result in an EnumConstantNotPresentException. In this case, the exception will be thrown because there is no enum constant with the name "VALUE4" in the MyEnum enumeration
In conclusion, unchecked exceptions are a powerful feature of Java that allows developers to handle runtime errors and exceptions in a structured way. By understanding the different types of unchecked exceptions in Java, developers can write more robust and reliable code that is less prone to crashes and unexpected behaviour.