JavaRush /Java Blog /Random EN /Coffee break #220. How to Fix Exceptions in Java - A Deta...

Coffee break #220. How to Fix Exceptions in Java - A Detailed Guide

Published in the Random EN group
Source: JavaTechOnline This tutorial will help you learn how to fix common exceptions in Java. In addition to the theory, you will see code examples to fix such problems. Coffee break #220.  How to Fix Exceptions in Java - A Detailed Guide - 1As with other programming languages, Java developers may encounter errors or exceptions when writing code. Exceptions should be taken seriously as their occurrence takes up work time. However, with a little knowledge, you can speed up the resolution of most of these problems. So, let's learn how to fix common exceptions in Java.

General Guidelines for Avoiding Exceptions in Java

To avoid throwing any exceptions in Java, it is important to understand and follow the coding guidelines:
  1. Always validate user input before using it in your code.
  2. Use try-catch , throws , throw blocks , depending on what is appropriate for a particular scenario.
  3. Do not neglect messages in the code about processing and errors. This will help identify and correct problems.
  4. Be sure to log exceptions for debugging purposes. You can use logger messages to help identify problems.
  5. Follow coding best practices to avoid exceptions and test your code thoroughly.
  6. Update your API dependencies to ensure you are using the latest and most stable versions of libraries and frameworks.
  7. Use the necessary tools and testing frameworks to identify potential problems in your code before they raise exceptions.
  8. Monitor your application's performance and logs to quickly identify and resolve any issues.
  9. Stay up to date with security best practices to ensure your code is secure and protected from any potential attacks.
  10. Document your code and its exceptions thoroughly to make it easier for other developers to understand and maintain.

List of the most common exceptions in Java

Java has a fairly long list of exceptions. Let's look at some of the most common:

NullPointerException

NullPointerException is a type of RuntimeException exception . It occurs when we try to use a reference variable that has a null value. This means that it points to an object or variable whose value is null . Such an error can occur when we try to call a method or access a field of an object that has not been initialized, or when we pass null as a parameter to a method that does not handle it. To prevent a NullPointerException from being thrown , you can check whether a reference variable is null using the == operator . If this is the case, then the null case needs to be handled correctly. Alternatively, we can initialize our variables to default values ​​(where possible) to ensure that we never encounter a null reference. Another way to avoid a NullPointerException is to use the Optional class . In Java, an Optional is a container object that may or may not contain a non-null value. It is used to represent the presence or absence of a value, similar to how the null value is used to represent the absence of a value. If a programmer tries to access the empty value of an Optional object , the program will not throw a NullPointerException but will instead return an empty Optional object . In other words, Optional forces the programmer to handle the case where the value is missing, which helps avoid a NullPointerException .

IndexOutOfBoundsException

IndexOutOfBoundsException is a runtime exception that is thrown when the index used to access an array or collection is negative or greater than or equal to the size of the array or collection. To prevent this exception from occurring, we must ensure that the index used to access the array or collection is within its bounds, that is, it must be greater than or equal to zero and less than the size of the array or collection.

ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException is a type of IndexOutOfBoundsException that is thrown when an attempt is made to access an array at an invalid index. In Java, array indices start at 0 and end at length()-1 , where length() is the number of elements in the array. If you try to access an element at an index outside this range, Java will throw an ArrayIndexOutOfBoundsException . When encountering an ArrayIndexOutOfBoundsException , you should review your code to ensure that you are using the correct indices when accessing the elements in the array.

StringIndexOutOfBoundsException

StringIndexOutOfBoundsException is an IndexOutOfBoundsException type that is thrown when an attempt is made to access a character in a string that has an invalid index. As with the previous ArrayIndexOutOfBoundsException , remember that in Java, the index of a string starts at 0 and ends at length()-1 , where length() is the number of characters in the string. If you try to access a character at an index outside this range, you may encounter a StringIndexOutOfBoundsException . If you encounter a StringIndexOutOfBoundsException , you should review your code to ensure you are using the correct indices when accessing characters in the string.

ClassCastException

This exception occurs when we try to cast an object to a type that is incompatible with its actual type. To solve a problem like this, it's important to make sure that your Java program only attempts to cast objects to the classes of which they are instances. You can check the type of an object using the instanceof operator before applying the cast.

IllegalArgumentException

IllegalArgumentException is a type of RuntimeException that is thrown when a method is called with an illegal or inappropriate argument. In other words, this error can occur when a method is called with an argument that is outside the expected range or does not have the expected format or structure. For example, a method requires a positive number as an argument and we provide a negative number, which is invalid input. If you encounter an IllegalArgumentException , you should check your code to ensure that you are calling methods with valid and appropriate arguments.

IllegalStateException

IllegalStateException is a type of RuntimeException that is thrown when an object is in an inappropriate state for the operation being performed. This can happen if a method is called on an object that is not in the expected state. For example, if we create a database connection object and then close it. Then if we try to create a Statement object in a closed connection, it will throw an IllegalStateException because the createStatement() method requires an open connection. If you encounter an IllegalStateException , you should review your code to ensure that you are calling methods on objects that are in the appropriate state.

UnsupportedOperationException

UnsupportedOperationException is a RuntimeException type that is thrown when an attempt is made to perform an unsupported operation on an object. This error can happen when we call a method that is not implemented by the object or is not supported by the object. To prevent an exception from being thrown, we should not call such operations that are not supported on objects. We need to review our code to make sure that we are calling methods on objects that support the operation.

ArithmeticException

ArithmeticException is a type of RuntimeException that is thrown when an arithmetic operation produces an invalid result. This exception can occur when we try to perform an arithmetic operation with an invalid or invalid argument. For example, when trying to divide by zero. To solve this problem, we can perform input validation and ensure that the arguments meet the required conditions before performing the arithmetic operation.

SecurityException

SecurityException is a type of RuntimeException that is thrown when a security violation occurs during program execution. This error can occur when a program attempts to perform an operation that is not permitted by security policy. To solve the problem, we must ensure that we have access to resources and perform operations for which we have specific permission.

NumberFormatException

NumberFormatException is a type of RuntimeException that is thrown when a method is called to convert a string to a number format, but the string is not in the appropriate format. To solve this problem, we must first validate the user's input before attempting to convert it. Also check your code to make sure you are trying to convert strings that are formatted appropriately for the target numeric type.

InterruptedException

InterruptedException is a checked exception that is thrown if a thread is waiting, sleeping, or blocking for some event and that event is interrupted by another thread. The error can occur when a thread is waiting for input, releasing a lock, or completing some other operation, and another thread interrupts the waiting thread. To resolve this issue, you can catch InterruptedException and respond by cleaning up resources, stopping the thread, or taking other appropriate action. If you encounter an InterruptedException , you should check your code to make sure you are handling thread interruptions correctly.

FileNotFoundException

FileNotFoundException is a checked exception that is thrown when a program tries to access a file that does not exist or cannot be found in the specified location. It can appear if a file is misspelled, moved or deleted, or even when a program does not have the necessary permissions to access the file. To fix the error, you can perform input validation to ensure that the file path is correct and that the program has the necessary permissions to access the file.

IOException

IOException is a checked exception in Java that represents an error encountered while performing input or output operations, such as reading or writing to a file or network socket. It can happen for several reasons, such as the specified file being missing or inaccessible, a network error, or insufficient permissions. To fix the problem, you need to perform several actions such as checking the error message, handling the exception using try-catch , closing resources, checking file permission, and so on.

NoSuchMethodException

NoSuchMethodException is an exception that is thrown at runtime when we try to call a method that does not exist in the class. This exception usually occurs if we call a method using Class.getMethod() or Class.getDeclaredMethod() and the specified method name is not found in the class or interface. An exception can also occur when we try to call a method using the java.lang.reflect.Method class and the specified method name does not exist in the object. To avoid this exception, be sure to call a valid method with the correct method signature and access specifier.

NoSuchFieldException

NoSuchFieldException is a runtime exception that occurs when we try to access a field that is not in the class. This exception usually occurs when we call a method using Class.getField() or Class.getDeclaredField() and the specified field name is not found in the class or interface. Additionally, it can also be called if we are trying to access a field using the java.lang.reflect.Field class and the specified field name does not exist in the object. To avoid this exception, make sure you are accessing a valid field with the correct name and access modifiers. If you are accessing a private field, be sure to use the getDeclaredField() method instead of the getField() method .

IllegalAccessException

IllegalAccessException is a run-time exception that occurs when we try to access a field or method in a class but we do not have the required access rights. This exception usually appears when we try to access a private field or method from outside a class or when we try to access a protected field or method from a class that is not a subclass of the original class. It can also be called when attempting to access a field or method that has been marked as unavailable by the java.lang.reflect.AccessibleObject class . To avoid this issue, make sure you have the necessary permissions on the field or method you are trying to access. If the field or method is private, you may need to use reflection and set AccessibleObject to true (to access it). However, be careful when using reflection to access private fields or methods, as it may break encapsulation and compromise the integrity of the class.

VerifyError

VerifyError is a run-time error that is a subclass of LinkageError . It occurs when the Java Virtual Machine (JVM) encounters a class file that violates certain validation rules. When a Java class is compiled, the compiler checks whether the bytecode follows certain rules and restrictions, such as type safety and proper use of the stack and local variables. If a class file violates these rules, the JVM will throw a VerifyError when loading and checking the class at runtime. To avoid VerifyError , make sure your code follows the correct syntax and semantics of the Java language. If you encounter a VerifyError , you should check your code to ensure that it is valid and that there are no violations of Java bytecode verification rules.

OutOfMemoryError

OutOfMemoryError is a subclass of Error , a Throwable type that introduces severe problems that cannot be resolved at runtime. Even though Java 8 includes some improvements in garbage collection and memory management, you may still encounter an OutOfMemoryError if your application is using too much memory or managing memory usage incorrectly. To avoid OutOfMemoryError , you need to properly manage memory usage in your Java application. This involves using data structures and algorithms that use memory efficiently, avoiding unnecessary object creation, and properly deleting objects when they are no longer needed. Additionally, you can increase the maximum heap size for the JVM by using the -Xmx flag when running your Java program.

StackOverflowError

StackOverflowError is a type of error that occurs when the stack size required by a program exceeds the amount of memory allocated to it. It can occur when a program calls too many nested methods or when a method calls itself recursively too many times, resulting in an infinite loop. The Java Virtual Machine (JVM) allocates a fixed amount of memory for the execution stack, which is used to keep track of method calls and local variables. When the stack overflows, the JVM throws a StackOverflowError . To avoid StackOverflowError , it is important to ensure that your Java program makes adequate use of recursion and method calls. If you encounter a StackOverflowError , you can try increasing the stack size by using the -Xss flag when running your Java program.

InvocationTargetException

InvocationTargetException is a checked exception that is thrown by the Java reflection mechanism. It is part of the java.lang.reflect.InvocationTargetException package and is used to indicate that an exception occurred during a method or constructor invocation. When a method or constructor is invoked using the Java reflection mechanism, the invoke() method of the java.lang.reflect.Method or java.lang.reflect.Constructor class is called . If the invoked method or constructor throws an exception, the invoke() method catches it and wraps it in an InvocationTargetException . This exception is then passed to the caller of the invoke() method . To fix the InvocationTargetException , we need to catch it, get the root cause exception using the getCause() method , and handle the root cause exception accordingly. Note that the root cause could be a checked exception or a runtime exception, so be sure to handle it correctly.

Ways to fix the most common exceptions in Java

How to fix NullPointerException

Scenario: You have a method that accesses an object that has the value null .
String title= null;
System.out.println(title.length()); // Это вызовет NullPointerException
Solution #1: Check if the object is null before use.
if(title!= null) {
   System.out.println(title.length());
} else {
   System.out.println("title is null");
}
Solution #2: Use Optional to avoid NullPointerException .
Optional<String> optionalTitle = Optional.ofNullable(getTitle());
if (optionalTitle.isPresent()) {
   String title= optionalTitle.get();
   System.out.println("Title: " + title);
} else {
   System.out.println("Title is not available.");
}

How to fix ArrayIndexOutOfBoundsException

Scenario: You are trying to access an array at an index that is outside its bounds.
int[] numbers = {4, 5, 6};
System.out.println(numbers[3]);   // Это вызовет ArrayIndexOutOfBoundsException
Solution: Check the length of the array before accessing it and make sure you are using valid indices.
int[] numbers = {4, 5, 6};
if (numbers.length > 3) {
   System.out.println(numbers[3]);
} else {
   System.out.println("ArrayIndexOutOfBoundsException: Please use valid indexes of the Array");
}

How to fix ClassCastException

Scenario: You are trying to cast an object to a type that is incompatible with its actual type.
Object obj = "Java Exception";
Integer number = (Integer) obj; // Это вызовет ClassCastException
Solution: Make sure you only cast objects to types that they are compatible with.
Object obj = "Java Exception";
if(obj instanceof Integer) {
   Integer number = (Integer) obj;
   System.out.println(number);
} else {
   System.out.println("Object cannot caste to Integer");
}

How to fix IllegalArgumentException

Scenario: You passed an invalid argument to a method.
public void printNumber(int number) {
   if(number <= 0) {
      throw new IllegalArgumentException("You cannot pass a negative number or zero");
   }
   System.out.println(number);
}

printNumber(-1); // Это вызовет IllegalArgumentException
Solution: Make sure you are passing valid arguments to methods. In this case, pass a positive number.
printNumber(1); //  Это успешно напечатает 1.

How to fix IllegalStateException

Scenario: The object is in an invalid state.
public class Bike {

   private Boolean isStarted;

   public void start() {
      if(isStarted) {
        throw new IllegalStateException("Bike is already started");
      }
      isStarted = true;
      System.out.println("Bike started");
   }
}

Bike bike= new Bike();
bike.start();
bike.start(); // Это вызовет IllegalStateException потому что bike is already started
Solution: Make sure you maintain object state correctly.
Bike bike= new Bike();
bike.start();

How to fix UnsupportedOperationException

Scenario: You use an operation that is not supported by an object. One popular example is when you use the remove() operation on an immutable collection, you will likely see an UnsupportedOperationException exception .
List<String> list = Arrays.asList("Java", "Angular", "Spring");
list.add("Python"); // Это вызовет UnsupportedOperationException
Because the Arrays.asList() method returns an immutable list, it does not support adding or removing elements. Solution: Make sure you only call supported operations on objects.
List<String> list = new ArrayList<>(Arrays.asList("Java", "Angular" "Spring"));
list.add("Python");
System.out.println(list);

How to fix ArithmeticException

Scenario #1: You are trying to perform an integer division operation that produces a fractional result.
int i = 10;
int j = 4;
int k = i/j; // Это вызовет исключение ArithmeticException: целочисленное деление будет дробным
Here the result of the division operation is 2.5, which is a fractional value. Because integers cannot store fractional values, an ArithmeticException is thrown . Solution: To avoid this exception, we can use a data type that supports fractional values, such as double , to store the result of the division operation. Here's an example:
int i = 10;
int j = 4;
double k = (double) i/j;
Scenario #2: You try to divide by zero and you get this exception. This is the most common scenario.
int i = 4;
int j = 0;
int k = i/j; // Это вызовет исключение ArithmeticException: нельзя делить на ноль
Solution: Handle division by zero correctly. For example, the code below demonstrates correct processing.
int i = 4;
int j = 0;
if(j != 0) {
int k = i/j;
System.out.println(k);
} else {
System.out.println("ArithmeticException: Cannot divide by zero");
}

How to fix IndexOutOfBoundsException

Scenario: You are trying to access a collection with an index that is outside of it.
List<String> list = Arrays.asList("Apple", "Papaya", "Mango");
System.out.println(list.get(3)); // Это вызовет IndexOutOfBoundsException
Solution: Check the size of the collection before accessing it and make sure you are using valid indexes.
List<String> list = Arrays.asList("Apple", "Papaya", "Mango");
if (list.size() > 3) {
   System.out.println(list.get(3));
} else {
   System.out.println("You are using the Index which is out of bounds");
}

How to fix IOException

Scenario: An input/output operation fails because the file is not accessible.
try {
   File inputFile = new FileReader("pqr.txt");
   BufferedReader reader = new BufferedReader(inputFile);
   String line = reader.readLine();
   System.out.println(line);
} catch (IOException e) {
   e.printStackTrace();
}
Solution: Handle I/O errors and ensure that resources are closed correctly.
File inputFile = new File("pqr.txt");

if (!inputFile.exists() || !inputFile.canRead()) {
 System.out.println("The input file is missing or not readable.");
 return;
}

try {
BufferedReader reader = new BufferedReader(inputFile);
 String line = reader.readLine();
 System.out.println(line);
  reader.close();
} catch (IOException e) {
 e.printStackTrace();
}
Note that as an alternative, we can use the try-with-resource feature introduced in Java 7 to automatically close resources as shown below. We can declare one or more resources in a try statement , and Java will automatically close the resources at the end of the block, regardless of whether the block completes normally or an exception is thrown.
try (BufferedReader reader = new BufferedReader(new FileReader("pqr.txt"))) {
....
} catch {
....
}

How to fix FileNotFoundException

Scenario: The file was not found in the specified location.
try {
     BufferedReader reader = new BufferedReader(new FileReader("abc.txt"));
     String line = reader.readLine();
     System.out.println(line);
     reader.close();
} catch (FileNotFoundException | IOException e) {
     System.out.println("An error has occurred while reading the file: " + e.getMessage());
}
Solution: Make sure the file exists and you have the appropriate permissions to access it.
try {
    File file = new File("abc.txt");
    if(!file.exists()) {
    throw new FileNotFoundException("File not found at the specified location");
    }
    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line = reader.readLine();
    System.out.println(line);
    reader.close();
} catch (IOException e) {
    e.printStackTrace();
}

How to fix NoSuchMethodException

Scenario: If you are trying to access a method that cannot be found.
public class TestClass {
   public void sayHello() {
      System.out.println("Hello");
   }
}

TestClass obj = new TestClass();
Method method = obj.getClass().getMethod("printHello"); // Это вызовет NoSuchMethodException
Solution: Verify that the method exists and that the method name and signature are correct.
public class TestClass {
   public void sayHello() {
      System.out.println("Hello");
   }
}

TestClass  obj = new TestClass();
try {
    Method method = obj.getClass().getMethod("sayHello");
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}

How to fix ConcurrentModificationException

Scenario: A collection changes while it is being iterated.
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
for (String str : list) {
  list.remove(str);  // Это вызовет ConcurrentModificationException
}
Solution: Use an iterator to iterate over a collection and modify it using iterator methods.
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String str = iterator.next();
    iterator.remove();
}
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION