Preface
In Java development, errors and exceptions are inevitable "frequently guests". Mastering the causes and solutions of common error types is the key to improving debugging efficiency and code robustness. This article classifies Java error reporting scenarios in the system and provides targeted solutions based on specific cases to help developers quickly locate and fix problems.
1. Runtime Exception (RuntimeException, non-checked exception)
1. NullPointerException (null pointer exception)
Cause of error
- Call
null
An instance method or property of an object (e.g.()
)。 - Uninitialized object references (e.g.
String str = null; int length = ();
)。
Sample code
public class NPEExample { public static void main(String[] args) { String text = null; (()); // Throw NullPointerException } }
Solution
-
Null value check:use
if (obj != null)
Or the three-point operator is judged in advance. -
Optional Packaging:pass
(obj)
Avoid direct operation of empty references. -
IDE prompts: Turn on the null value analysis of the IDE (such as IntelliJ's
@Nullable
/@NonNull
annotation check).
2. ArrayIndexOutOfBoundsException (array out of bounds exception)
Cause of error
- The index is out of range when accessing an array (such as an array of length 5, index 5 or -1).
Sample code
public class ArrayError { public static void main(String[] args) { int[] arr = {1, 2, 3}; (arr[3]); // Index 3 exceeds array length 3, throws an exception } }
Solution
-
Boundary verification:use
if (index >= 0 && index < )
Check index legality. -
Loop traversal: Priority
for-each
Looping avoids manual control of indexes (suitable for scenarios where no index is required).
3. ClassCastException (type conversion exception)
Cause of error
- Casting incompatible types (such as
String
Convert toInteger
, or a non-inheritance conversion of a subclass object to a parent class).
Sample code
public class CastError { public static void main(String[] args) { Object obj = "hello"; Integer num = (Integer) obj; // The string cannot be converted to Integer, throws an exception } }
Solution
-
Type Check: Used before conversion
instanceof
Determine type (e.g.if (obj instanceof Integer)
)。 -
Generic constraints: Reduce cast using generics (e.g.
List<String> list = (List<String>) obj;
)。
4. IllegalArgumentException (illegal parameter exception)
Cause of error
- The method passes in parameters that do not meet the requirements (such as
(-1)
, negative index).
Sample code
public class ArgError { public static void main(String[] args) { String str = "abc"; (4); // Index 4 exceeds string length 3, throws an exception } }
Solution
-
Parameter verification: Add parameter legality check at the method entrance (such as
if (index < 0) throw new IllegalArgumentException("Index cannot be negative")
)。
2. Compile-Time Error (Compile-Time Error, syntax or logic error)
1. SyntaxError (Syntax Error)
Cause of error
- The code does not comply with Java syntax rules (such as missing semicolons, mismatched brackets, and misspelled keywords).
Example
public class SyntaxError { public static void main(String[] args) { ("hello world) // The right quote is missing, the compilation is reported by an error } }
Solution
- IDE assist: Use the IDE's syntax highlighting and real-time error prompts (such as red wavy lines marking the error position).
- Check line by line: Pay attention to the line number and error description in the compiler error message (such as "unclosed string literal" prompts that the quotes are not closed).
2. CannotResolveSymbol (symbol cannot be parsed)
Cause of error
- References to undeclared variables, classes, or methods (such as misspelling, unimported packages, and error scoped).
Sample code
import ; public class SymbolError { public static void main(String[] args) { Dte date = new Dte(); // Class name spelling error (should be Date), compile error } }
Solution
-
Check import: Make sure the class has been imported correctly (e.g.
import ;
), or use a fully qualified name (date = new ();
)。 - Variable declaration: Confirm that the variable has been declared before use and the scope is correct (such as local variables are not used outside the method).
3. IncompatibleTypes (type incompatible)
Cause of error
- Types do not match when assigning or passing parameters (such as
int
Assign toString
, or the method parameter type is incorrect).
Sample code
public class TypeError { public static void main(String[] args) { int num = "123"; // Cannot assign String to int, compile error } }
Solution
-
Explicit conversion: Use casting for basic types (e.g.
int num = ("123");
), the object type needs to satisfy the inheritance relationship.
3. Error class (unrecoverable error, usually a JVM-level problem)
1. OutOfMemoryError (memory overflow error)
Cause of error
- The JVM heap is insufficient (such as creating a large number of objects that are not released, or memory leaks that cause GC to not be recycled).
Sample Scenario
- Create an object in infinite loop:
List<Object> list = new ArrayList<>(); while (true) { (new byte[1024 * 1024]); // Each time 1MB of data is added, the heap memory will eventually run out}
Solution
-
Increase the heap memory: Pass JVM parameters
-Xmx2g
Expand the heap memory limit (production environment needs to be evaluated based on business). - Memory leak troubleshooting: Use tools (such as VisualVM, MAT) to analyze the heap dump file and locate unreleased objects.
-
Optimize object life cycle: Timely release objects that are no longer used (if set as
null
, or use try-with-resources to close the resource).
2. *Error (stack overflow error)
Cause of error
- Methods are called too deep (such as recursion without termination conditions), or too many stack frames exceed the stack memory limit.
Sample code
public class RecursionError { public static void recursiveMethod() { recursiveMethod(); // Infinite recursion, the stack depth continues to increase } public static void main(String[] args) { recursiveMethod(); // Throw *Error } }
Solution
-
Check recursive logic: Ensure that there are termination conditions for recursion (such as adding baseline conditions
if (n == 0) return;
)。 - Reduce stack depth: Change recursion to iterative (such as using a loop instead of recursive calculation of factorials).
3. NoClassDefFoundError (ClassDefFoundError)
Cause of error
- The class that existed at compile time cannot be found during the runtime (such as missing dependency package, class name change, class file corruption).
Sample Scenario
- Deleted from the project
class, but other classes still refer to the class:
public class Main { public static void main(String[] args) { (); // The Helper class does not exist at runtime, throws an error } }
Solution
-
Check dependencies: Make sure all dependency packages are correctly introduced (such as Maven project checking
Is the dependency missing?).
- Recompile: Clean and rebuild the project to ensure that the class file is generated correctly.
4. Other common types of errors
1. IOException (IO exception, detected exception)
Cause of error
- An error occurred during IO operations such as file reading and writing, network connection, etc. (such as the file does not exist and insufficient permissions).
Sample code
import ; import ; public class IOError { public static void main(String[] args) throws IOException { FileReader reader = new FileReader(""); // The file does not exist, throws an exception } }
Solution
-
Exception handling:use
try-catch
Capture and process (e.g.catch (FileNotFoundException e) { ... }
), or declare thrown (throws IOException
)。 -
Resource Close:pass
try-with-resources
Automatically close IO resources (avoid resource leakage).
2. ClassNotFoundException (class no exception found)
Cause of error
- use
()
When loading the class, the class name is wrong or the jar package where the class is located is not included in the classpath.
Sample code
public class ClassNotFound { public static void main(String[] args) throws ClassNotFoundException { (""); // The class does not exist, throws an exception } }
Solution
- Check the class name: Ensure that the class name and package path are correct (case sensitive).
-
Add dependencies: Confirm that the jar package where the class is located has been added to the project build path (such as Maven's
dependency
configuration).
3. ConcurrentModificationException (concurrent modification exception)
Cause of error
- When iterating the set (such as
for-each
loop), other threads or the current thread have modified the collection structure (add/remove elements).
Sample code
import ; import ; public class ConcurrentModification { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); ("a"); ("b"); Iterator<String> iterator = (); while (()) { String item = (); (item); // Delete elements during iteration and throw an exception } } }
Solution
-
Use iterator to delete:pass
()
Instead of the collection itselfremove()
method. -
Concurrent collection: Use thread-safe collections instead (e.g.
CopyOnWriteArrayList
) or lock control.
5. General process and best practices for error investigation
1. Understand the error message
-
Positioning key information: Pay attention to the type of error (such as
NullPointerException
), error message (such asnull
), line number (such asat (:10)
)。 -
Distinguish between tested and untested abnormalities: Exactly detected abnormalities (such as
IOException
) must be handled explicitly, and the non-checked exception (e.g.RuntimeException
) needs to be avoided logically.
2. Step-by-step debugging
- Breakpoint debugging: Use the IDE's debugging function (such as IntelliJ's Debug mode), track variable values and execution flow line by line.
- Minimize recurrence: Simplify the error reporting scenario to a minimum runnable example (such as single-class test cases), and eliminate other code interference.
3. Exception handling principles
-
Targeted capture: Priority to catch specific exceptions (such as
FileNotFoundException
), not universalException
, avoid covering up real problems. -
Logging:exist
catch
Record detailed logs (including exception stack and parameter information) in the block for easy subsequent analysis (such as using("Error Message", e)
)。
4. Preventive measures
-
Defensive programming: Verify the legality of the method parameters and external input (if used
()
)。 -
Unit Testing: Write test cases covering boundary conditions and exception scenarios (such as Junit's
assertThrows
)。
6. Summary: Accumulate experience from mistakes
Although there are many types of errors in Java, the core can be summarized asSyntax errors, logical exceptions, resource problems, JVM-level errorsFour categories. Mastering typical scenarios and solutions for each error, combining IDE tools and debugging skills can greatly improve problem positioning efficiency. remember:Reasonable exception handling is not omnipotent, and more importantly, it reduces error occurrence through robust code design.——such as strict null value checking, clear recursive termination conditions, and reasonable resource management.
When encountering unknown errors, make good use of search engines and official documents (such as Java API documents, error code explanations), and learn to extract key clues from the exception stack. By continuously accumulating error handling experience, developers can gradually improve the stability and maintainability of their code and respond freely in the development of complex systems.
This is the article about common Java error types and solutions. For more relevant Java error types, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!