Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
ArrayStoreException in Java
Next article icon

Errors V/s Exceptions In Java

Last Updated : 01 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, errors and exceptions are both types of throwable objects, but they represent different types of problems that can occur during the execution of a program.

Errors are usually caused by serious problems that are outside the control of the program, such as running out of memory or a system crash. Errors are represented by the Error class and its subclasses. Some common examples of errors in Java include:

  • OutOfMemoryError: Thrown when the Java Virtual Machine (JVM) runs out of memory.
  • StackOverflowError: Thrown when the call stack overflows due to too many method invocations.
  • NoClassDefFoundError: Thrown when a required class cannot be found.

Since errors are generally caused by problems that cannot be recovered from, it’s usually not appropriate for a program to catch errors. Instead, the best course of action is usually to log the error and exit the program.

Exceptions, on the other hand, are used to handle errors that can be recovered from within the program. Exceptions are represented by the Exception class and its subclasses. Some common examples of exceptions in Java include:

  • NullPointerException: Thrown when a null reference is accessed.
  • IllegalArgumentException: Thrown when an illegal argument is passed to a method.
  • IOException: Thrown when an I/O operation fails.

Since exceptions can be caught and handled within a program, it’s common to include code to catch and handle exceptions in Java programs. By handling exceptions, you can provide more informative error messages to users and prevent the program from crashing.

In summary, errors and exceptions represent different types of problems that can occur during program execution. Errors are usually caused by serious problems that cannot be recovered from, while exceptions are used to handle recoverable errors within a program.

In java, both Errors and Exceptions are the subclasses of java.lang.Throwable class. Error refers to an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing. It is of three types:

  • Compile-time
  • Run-time
  • Logical

Whereas exceptions in java refer to an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions.

Now let us discuss various types of errors in order to get a better understanding over arrays. As discussed in the header an error indicates serious problems that a reasonable application should not try to catch. Errors are conditions that cannot get recovered by any handling techniques. It surely causes termination of the program abnormally. Errors belong to unchecked type and mostly occur at runtime. Some of the examples of errors are Out of memory errors or System crash errors. 

Example 1 Run-time Error

Java




// Java Program to Illustrate Error
// Stack overflow error via infinite recursion
 
// Class 1
class StackOverflow {
 
    // method of this class
    public static void test(int i)
    {
        // No correct as base condition leads to
        // non-stop recursion.
        if (i == 0)
            return;
        else {
            test(i++);
        }
    }
}
 
// Class 2
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Testing for error by passing
        // custom integer as an argument
        StackOverflow.test(5);
    }
}
 
 

Output: 

https://media.geeksforgeeks.org/wp-content/uploads/20210906064258/stackOverFlowError.jpeg.mp4

Example 2

Java




// Java Program to Illustrate Run-time Errors
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Declaring and initializing numbers
        int a = 2, b = 8, c = 6;
 
        if (a > b && a > c)
            System.out.println(a
                               + " is the largest Number");
        else if (b > a && b > c)
            System.out.println(b
                               + " is the smallest Number");
 
        // The correct message should have been
        // System.out.println
        // (b+" is the largest Number"); to make logic
        else
            System.out.println(c
                               + " is the largest Number");
    }
}
 
 
Output
8 is the smallest Number     

Now let us dwell onto Exceptions which indicates conditions that a reasonable application might want to catch. Exceptions are the conditions that occur at runtime and may cause the termination of the program. But they are recoverable using try, catch and throw keywords. Exceptions are divided into two categories:

  • Checked exceptions
  • Unchecked exceptions

Checked exceptions like IOException known to the compiler at compile time while unchecked exceptions like ArrayIndexOutOfBoundException known to the compiler at runtime. It is mostly caused by the program written by the programmer.

Example Exception

Java




// Java program illustrating exception thrown
// by Arithmetic Exception class
 
// Main class
class GFG {
 
    // main driver method
    public static void main(String[] args)
    {
        int a = 5, b = 0;
 
        // Try-catch block to check and handle exceptions
        try {
 
            // Attempting to divide by zero
            int c = a / b;
        }
        catch (ArithmeticException e) {
 
            // Displaying line number where exception occurred
            // using printStackTrace() method
            e.printStackTrace();
        }
    }
}
 
 

Output: 

Finally now wrapping-off the article by plotting the differences out between them in a tabular format as provided below as follows:

Errors Exceptions
Recovering from Error is not possible. We can recover from exceptions by either using try-catch block or throwing exceptions back to the caller.
All errors in java are unchecked type. Exceptions include both checked as well as unchecked type.
Errors are mostly caused by the environment in which program is running. Program itself is responsible for causing exceptions.

Errors can occur at compile time.

Unchecked exceptions occur at runtime whereas checked exceptions occur at compile time
They are defined in java.lang.Error package. They are defined in java.lang.Exception package
Examples : java.lang.StackOverflowError, java.lang.OutOfMemoryError Examples : Checked Exceptions : SQLException, IOException Unchecked Exceptions : ArrayIndexOutOfBoundException, NullPointerException, ArithmeticException.


Next Article
ArrayStoreException in Java

A

AnushkaKhattri
Improve
Article Tags :
  • Java
  • Java-Exception Handling
  • Java-Exceptions
Practice Tags :
  • Java

Similar Reads

  • ArrayStoreException in Java
    ArrayStoreException in Java occurs whenever an attempt is made to store the wrong type of object into an array of objects. The ArrayStoreException is a class which extends RuntimeException, which means that it is an exception thrown at the runtime. Class Hierarchy: java.lang.Object ↳ java.lang
    2 min read
  • Chained Exceptions in Java
    Chained Exceptions in Java allow associating one exception with another, i.e. one exception describes the cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero, but the root cause of the error was an I/O
    3 min read
  • Top 5 Exceptions in Java with Examples
    An unexpected unwanted event that disturbs the program's normal execution after getting compiled while running is called an exception. In order to deal with such abrupt execution of the program, exception handling is the expected termination of the program.  Illustration: Considering a real-life exa
    5 min read
  • Types of Exception in Java with Examples
    Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situati
    8 min read
  • Best Practices to Handle Exceptions in Java
    Exception Handling is a critical aspect of Java programming, and following best practices for exception handling becomes even more important at the industry level where software is expected to be highly reliable, maintainable, and scalable. In this article, we will discuss some of the best practices
    7 min read
  • Array Index Out Of Bounds Exception in Java
    In Java, ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program. It occurs when we try to access the element out of the index we are allowed to, i.e. index >= size of the array. Java support
    4 min read
  • Java Exception Handling
    Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program (i.e., at runt
    10 min read
  • How to Solve Class Cast Exceptions in Java?
    An unexcepted, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating at the U.S.A. At runtime, if the remote fi
    3 min read
  • User-Defined Custom Exception in Java
    In Java, an Exception is an issue (run-time error) that occurs during the execution of a program. When an exception occurs, the program terminates abruptly, and the code beyond the exception never gets executed. Java provides us the facility to create our own exceptions by extending the Exception cl
    4 min read
  • Null Pointer Exception in Java
    A NullPointerException in Java is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value. Example: [GFGTABS] Java // Demonstration of NullPointerException in J
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences