Difference Between Errors and Exceptions in
Java
Anshuman Singh
Senior Execut ive - Cont ent
Updated on Feb 19, 2024 12:33 IST
In Java, one of the main difference between errors and exceptions is that errors
represent severe issues that indicate resource exhaustion or system problems
beyond the program's control. Recovering f rom an error is generally
impossible . On the other hand, exceptions represent unexpected events that
occur during program execution due to issues within the code itself. These can
of ten be handled using try-catch blocks to provide alternative behaviour or
informative messages.
In Java, both errors and exceptions are subclasses of the Java Throwable class
that belongs to java.lang package. Even though both are the subclass of the
same class, they represent distinct issues that can arise during program execution.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 20 -Feb-20 24.
Table of Content (TOC)
Dif f erence Between Errors and Exceptions
What are Errors?
Error Example
What are Exceptions?
Exception Example
Key Dif f erences Between Errors and Exceptions
Difference Between Errors and Exceptions
For better clarity, let's comprehend the difference between these two subclasses in
a tabular format.
Aspect Error Exception
A serious problem that An issue that can disrupt
cannot be recovered the normal f low of a
Def inition
f rom, typically arising program but can be caught
f rom system-level issues. and handled.
System abnormalities
Application code, including
such as hardware
Origin invalid input or incorrect
f ailures, system crashes,
API usage.
or out of memory.
Can of ten be recovered
Fatal and non- f rom using try-catch
Recovery
recoverable. blocks.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 20 -Feb-20 24.
Aspect Error Exception
Checked Exceptions
(detected at compile time)
Syntax Error, Runtime
Types and Unchecked
Error, Logical Error.
Exceptions (occur at
runtime).
IOException,
OutOf MemoryError,
Examples NullPointerException,
StackOverf lowError.
SQLException, etc.
Can be caught and
Cannot be handled or handled in the program to
Handling
caught by the program. maintain f low or recover
f rom the situation.
Hierarchy in Extends the Error class in Extends the Exception
Java in Java’s class hierarchy. class in the hierarchy.
Primarily occur at runtime,
When They Can occur both at though checked
Occur compile time and runtime. exceptions can be
detected at compile time.
Disrupts the normal f low
May cause the program
but allows f or redirection
Impact (and potentially the
or handling within the
system) to terminate.
program.
Unpredictable and of ten Can be anticipated and
Predictability outside the control of the handled through proper
application. coding practices.
You should also explore: Features of Java Programming Language
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 20 -Feb-20 24.
What are Errors?
Errors in Java denote serious issues that majorly occur at runtime due to external
factors beyond the program's control. Common causes of these errors include
critical system failures and resource limitations, such as running out of memory or
encountering a stack overflow.
Due to their gravity, errors are represented by the Error class and its subclasses.
Attempting to recover from them within the program is nearly impossible. Instead,
the recommended approach is to log the error and exit the application. Some
common examples of Java errors are:
OutOf MemoryError: Occurs when the Java Virtual Machine (JVM)
exhausts available memory resources.
StackOverf lowError: Arises when the call stack becomes too deep
due to excessive method invocations.
NoClassDef FoundError: Triggered when the JVM cannot locate a
required class.
Error Example: OutOfMemoryError
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 20 -Feb-20 24.
Copy code
public class ErrorExample {
public static void main(String[] args) {
try {
// Intentionally create an array size that is too large to fit into memory
int[] largeArray = new int[Integer.MAX_VALUE];
} catch (Throwable e) {
// Catch the OutOfMemoryError
System.out.println(e.toString());
}
}
}
Output:
Explanation: This example tries to allocate an array that's too large for the JVM's
memory, causing an OutOfMemoryError. This error is caught by catching Throwable
(the superclass of all errors and exceptions), and its type is printed. Usually, catching
such errors is not recommended unless you're doing specific error handling or
logging, as it indicates issues that an application usually cannot recover from by
itself.
What are Exceptions?
Exceptions in Java are issues that occur within a program and disrupt the normal
flow of its execution. These can be recoverable errors like NullPointerException and
IllegalArgumentException. Java has two types of exceptions: checked and
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 20 -Feb-20 24.
unchecked. They differ in their handling requirements.
Checked Exceptions: These are known to the compiler at compile
time, necessitating explicit handling within the code.
Unchecked Exceptions: These are detected at runtime and are
typically caused by programming errors, allowing f or more f lexibility in
handling.
Developers can use try-catch blocks to manage exceptions effectively. This allows
them to provide informative error messages to users and prevent program crashes.
Must Explore: Exception Handling in Java
Exception Example: FileNotFoundException
Copy code
import java.io.File;
import java.io.FileReader;
public class ExceptionExample {
public static void main(String[] args) {
try {
// Attempt to open a file that does not exist
File file = new File("nonexistent.txt");
FileReader fr = new FileReader(file);
} catch (java.io.FileNotFoundException e) {
// Catch the FileNotFoundException
System.out.println(e.toString());
}
}
}
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 20 -Feb-20 24.
Output:
Explanation: This example attempts to open a file that does not exist, which
throws a FileNotFoundException, a checked exception. The catch block catches this
exception and prints its type and message. Unlike errors, exceptions like
FileNotFoundException are expected to be handled by applications to either recover
from the condition or provide informative feedback to the user.
Key Differences Between Errors and Exceptions
Here are the key differences between errors and exceptions:
Errors indicate unrecoverable system issues beyond program control.
In contrast, exceptions represent unexpected events within the
program that can of ten be handled gracef ully.
All errors are subclasses of the java.lang.Error class. Meanwhile, all
exceptions are subclasses of the java.lang.Exception class, which
itself inherits f rom java.lang.Throwable.
In Java, errors occur at runtime when the system encounters
resource limitations. In contrast, exceptions occur both at runtime
and compile time.
Due to their unrecoverable nature, errors are not meant to be caught
within the program. In contrast, exceptions can be caught and
handled using try-catch blocks.
You can also read:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 20 -Feb-20 24.
Final Keyword in Java
The Final Keywo rd in Java allo ws declaring a class, data members, and
metho ds to unalterable and behaves differently when it is used with classes,
metho ds, and variables. In this article,...re ad m o re
Super Keyword in Java
This Java Tuto rial article co vers o ne o f the mo st impo rtant co ncepts in
Inheritance which is Super Keywo rd in Java. Here, we’ll go thro ugh the uses o f
super keywo rd alo ng with...re ad m o re
Access Modif iers in Java
Access mo difiers are keywo rds that define the accessibility o f a class and its
members. Access mo difiers are used in Java to co ntro l the visibility
(accessibility) o f classes, interfaces, variables, metho ds,...re ad m o re
Jump St at ement s in Java
In this article, we’ll co ver the Jump Statements in Java, such as break, co ntinue
and return, alo ng with examples and explanatio ns.
Loops in Java Explained
The belo w article co vers the iteratio n statements o r lo o ps in Java. It go es
thro ugh the wo rking o f lo o ps with implementatio n and examples.
Condit ional St at ement s in Java
The belo w article go es thro ugh the Co nditio nal Statements in Java. It co vers if,
if-else, nested if-else, and switch statements with examples.
Reverse a St ring in Java
Reversing a string is a co mmo n pro gramming pro blem given while learning
ho w to co de and invo ke lo gical thinking. Ho wever, there are mo re than o ne
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 20 -Feb-20 24.
ways to so lve this pro blem. The...re ad m o re
Java Operat ors Explained
In this article, we’ll co ver several o perato rs in Java with examples. Mo reo ver, the
article go es thro ugh o perato r precedence.
Underst anding Variables in Java
Have yo u ever wo ndered ho w data is sto red and manipulated in Java
pro grams? Variables in Java are the answer, acting as co ntainers fo r data
values. Each variable is defined with...re ad m o re
Get t ing St art ed wit h Java Hello World Program
Do yo u kno w the significance o f the "Hello Wo rld" pro gram in Java? It's the first
step fo r many into the wo rld o f pro gramming, serving as a simple yet pro fo und
intro ductio n...re ad m o re
Dif f erence bet ween JDK, JRE, and JVM
The article go es thro ugh explaining Java Virtual Machine (JVM), Java Runtime
Enviro nment (JRE), and Java Develo pment Kit (JDK) in detail. Mo reo ver, it
co vers the differences between JVM, JRE, and JDK.
Implement ing Array in Java
Arrays in Java help to maintain elements o f same datatype under a single
variable name. The belo w article explains the implementatio n o f array in java
with examples.
Except ion Handling in Java
Exceptio n Handling in Java is a way to tackle abno rmal o ccurrences which
interrupts the no rmal flo w o f the pro gram.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 20 -Feb-20 24.
Underst anding OOPs Concept s in Java
Object o riented pro gramming (OOP) co ncepts are the fundamental pillars o f
pro gramming. The article belo w explains the OOPs co ncept in Java. It co vers
intro ductio ns to OOPs, class, o bjects, inheritance, abstractio n,
encapsulatio n,...re ad m o re
The Key Dif f erence Bet ween C++ and Java
C++ and Java are two po pular pro gramming languages that are widely used by
pro grammers. Bo th languages have significant applicatio ns and this is why they
have beco me po pular o ver years.
FAQs
How do exceptions dif f er f rom errors?
Can all errors and exceptions be prevented in Java programming?
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 20 -Feb-20 24.