Back to: Java Tutorials
In Java, the terms “exception” and “error” have specific meanings and are used to differentiate between different types of problems that can occur in a program.
Exceptions are a type of error that can occur during the normal operation of a program, but are not necessarily fatal. Exceptions represent conditions that can be handled by the program, either by the code that caused the exception or by other parts of the program. Examples of exceptions in Java include NullPointerException
, ArrayIndexOutOfBoundsException
, and ArithmeticException
. Exceptions are typically handled using try-catch blocks, where the code that might throw an exception is placed in the try block and the exception handling code is placed in the catch block.
Errors, on the other hand, represent more serious problems that typically cannot be recovered from. Errors are usually caused by external factors that are outside the control of the program, such as a lack of system resources, a stack overflow, or an unrecoverable hardware failure. Examples of errors in Java include OutOfMemoryError
, StackOverflowError
, and VirtualMachineError
. Unlike exceptions, errors are not typically caught and handled by the program, as there is usually no way to recover from them.
In summary, exceptions are used to handle recoverable problems that can occur during the normal operation of a program, while errors represent more serious problems that typically cannot be recovered from.
Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.