Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
A Brief Explanation of Errors
2.1.
OutOfMemoryError in Java
2.2.
CODE
2.2.1.
 
2.2.2.
OUTPUT
2.3.
StackOverflowError in Java
2.4.
CODE
2.4.1.
 
2.4.2.
OUTPUT
2.5.
NoClassDefFoundError in Java
2.6.
CODE
2.6.1.
 
2.6.2.
OUTPUT
3.
Methods for Error Handling
3.1.
Generating special exceptions
3.2.
CODE
3.2.1.
 
3.2.2.
OUTPUT
3.3.
Using third-party frameworks and libraries 
3.4.
CODE
3.4.1.
 
3.4.2.
OUTPUT
4.
Methods for Exception Handling
4.1.
Try-catch-finally blocks
4.2.
CODE
4.2.1.
 
4.2.2.
OUTPUT
4.3.
Handling with exception handlers
4.4.
CODE
4.4.1.
 
4.4.2.
OUTPUT 
5.
Comparison Table between Error and Exception
6.
Frequently Asked Questions
6.1.
What is the difference between error and exception in Java?
6.2.
Can you describe the stack trace concept in exception handling?
6.3.
In Java, how do you make your unique exception?
6.4.
What does the finally block in exception handling accomplish?
6.5.
What function does the try-catch block serve in handling exceptions?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Difference between Error and Exception

Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Hey Ninjas, Have you ever faced problems with the difference between error and exception? Have you ever thought why it's crucial to understand the difference between error and exception in Java and to create efficient plans for handling these problems?

Your software systems would be vulnerable to bugs and crashes that could harm the software.

Difference Between Error and Exception

This article examines the difference between error and exception and several techniques and methods for handling these problems in software development. 

So let's investigate the world of difference between error and exception.

Also read, Duck Number in Java and Hashcode Method in Java

A Brief Explanation of Errors

In Java, an error is a subclass of throwable that indicates serious problems that a reasonable application should not try to catch. Errors are typically low-level issues that can arise from problems with the software or the setting in which it operates. OutOfMemoryError, StackOverflowError, and NoClassDefFoundError are a few examples of errors in Java. Errors are typically not recoverable by application code and may call for higher-level help.

Explanation about Errors

A few examples of Java errors are 

  • Compile-time errors that the compiler detects during compilation, such as syntax mistakes and type mismatches, which are frequent errors in Java.
     
  • Runtime errors occur while the program is being executed and can result in abnormal program termination, including NullPointerException and DivideByZero errors.
     
  • System errors are caused by issues unrelated to the application, such as hardware malfunctions or network connectivity problems.

OutOfMemoryError in Java

An OutOfMemoryError occurs when insufficient memory is available to allocate an object. This can also happen when a program tries to create too many large objects.

Here is an example code that can trigger an OutOfMemoryError in Java:

CODE

import java.util.ArrayList;
import java.util.List;

//First, define the OutOfMemoryErrorExample class
public class OutOfMemoryErrorExample {
    public static void main(String[] args) {
        
        // Now create an ArrayList to store a list of objects
        List<Object> objects = new ArrayList<>();
        
        //This infinite loop will keep adding new objects to the list until the program runs out of memory
        while (true) {
            objects.add(new Object());
        }
    }
}

 

OUTPUT

output


When this code keeps adding new Object instances to an ArrayList after the Java heap runs out of memory, the program crashes due to an OutOfMemoryError.

StackOverflowError in Java

A StackOverflowError occurs when the call stack exceeds its maximum allowed size. This can happen due to a badly written recursive function.

Here's an example code that can trigger a StackOverflowError in Java:

CODE

//First, define the StackOverflowErrorExample class
public class StackOverflowErrorExample {
    public static void main(String[] args) {
        
        // Call the recursiveFunction method with 0
        recursiveFunction(0);
    }
    
    // Recursive function that calls itself indefinitely increments the value by one each time
    public static void recursiveFunction(int num) {
        
        // Now print the current value of the num
        System.out.println(num);
        recursiveFunction(num + 1);
    }
}

 

OUTPUT

output

 

Output

This code causes the program to crash by repeatedly invoking the recursiveFunction method with increasing integer values, which expands the call stack until it exceeds the available stack memory.

Also see,  Swap Function in Java

NoClassDefFoundError in Java

NoClassDefFoundError is a Java error that occurs when the compiler looks for the definition of a class in its internal structure and does not find it.

CODE

// First, define the NoClassDefFoundErrorExample class
public class NoClassDefFoundErrorExample {
    public static void main(String[] args) {
        
        // try to create an instance of the MyCustomClass class
        MyCustomClass myCustomClass = new MyCustomClass();
    }
}
class MyCustomClass {  
    // define an empty class
}

 

OUTPUT

output

If the MyCustomClass class cannot be found at runtime due to improper compilation or absence from the classpath, this code may result in a NoClassDefFoundError error. An error is generated when the JVM tries to load and link the class during runtime but is unsuccessful.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Methods for Error Handling

The process of locating, catching, and recovering from errors during program execution is known as error handling in Java. This involves handling exceptions with try-catch blocks and ensuring the proper steps are taken to recover from mistakes and prevent program crashes.

Per the requirements of your application and the potential types of errors, you must select the best error-handling strategy.

Methods for Error Handling

Typical Java error-handling techniques include:

Generating special exceptions

Java allows for generating unique exceptions, which can be used to design custom exceptions to address particular application errors. You can give more context-specific information about the error and facilitate debugging and problem-solving by creating specific exceptions.

Here's an example of generating a unique exception in Java:

CODE

public class Main {
public static void main(String[] args) {
try {
            
            // First, call the square() function with a negative number to get a NegativeNumberException 
            int result = square(-5);
            System.out.println("Result is " + result);
     } catch (NegativeNumberException e) {
            
            // catch and handle the exception
            System.out.println("Error is  " + e.getMessage());
        }
    }
		
		//The square() function will throw a NegativeNumberException if you will negative input number.
public static int square(int n) throws NegativeNumberException {
        if (n < 0) {
            throw new NegativeNumberException("Number cannot be negative");
        }
        return n * n;
    }
}
	
	// Here, the NegativeNumberException class extends the Exception class to create a custom exception for negative input numbers
class NegativeNumberException extends Exception {
    public NegativeNumberException(String message) {
        super(message);
    }
}

 

OUTPUT

output

When running, this program will call the square method with a negative number, resulting in a NegativeNumberException. The catch block will catch this exception, printing the error to the console. If you use a positive number to call the square method, the squared value of that number will be returned and printed to the console.

Using third-party frameworks and libraries 

You can implement more complex and efficient error handling in your application using third-party frameworks and libraries for Java. These frameworks and libraries offer a variety of features and tools to handle mistakes and manage them more streamlined and effectively.

Here's an example of using this library to handle errors:

CODE

// It is important to import the class from the Apache Commons Lang library 
import org.apache.commons.lang3.exception.ExceptionUtils;
public class Main {
public static void main(String[] args) {
try {
// call the divide() function for two numbers to perform division
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
// here, catch and handle by getting the error message and trace using the ExceptionUtils class
            String message = ExceptionUtils.getMessage(e);
            String stackTrace = ExceptionUtils.getStackTrace(e);
            System.out.println("Error message: " + message);
            System.out.println("Stack trace: " + stackTrace);
        }
    }


    public static int divide(int a, int b) {
        return a / b;
    }
}

 

OUTPUT

output

We use the org.apache.commons.lang3.exception in this example. When we try to divide by zero, the ExceptionUtils class from the Apache Commons Lang library will produce a more detailed error message. The error message and the stack trace are obtained using the getMessage and getStackTrace methods, respectively.

Methods for Exception Handling

Runtime errors, also known as exceptional events, can be handled by programmers in their programs using the exception-handling mechanism in Java. Java offers a built-in framework for handling exceptions, enabling programmers to catch and manage errors. Exception handling aims to keep the program running normally, even in unexpected events. 

Some common exception-handling techniques in Java include:

Try-catch-finally blocks

The try block contains the code that will produce an exception. The catch block contains the code that handles the exception if it occurs. The final block contains executed code, no matter whether an exception is thrown or not.

Here's an example of using a try-catch-finally block to handle exceptions in Java:

CODE

public class Example {
  public static void main(String[] args) {
    try {
    
    // An integer variable x is assigned the result of dividing 10 by 0.
      int x = 10 / 0; 
    } catch (ArithmeticException e) {
  
    // If an ArithmeticException occurs, the catch block is executed, printing an error message.
      System.out.println("An arithmetic exception occurred: " + e.getMessage());
    } finally {
    
    // The final block always executes, regardless of whether an exception occurs. 
      System.out.println("This code will always execute.");
    }
  }
}

 

OUTPUT

Output

The try block in this example contains code that could raise an ArithmeticException. When this exception is thrown, the catch block will catch and handle it by printing a message. The final block's code is always carried out regardless of whether an exception was raised.

Try catch and exception handlers

Handling with exception handlers

It has the try block, which contains the code that may produce an exception. The catch block contains the code that handles the exception if it occurs.

Here's an example of handling a particular exception type with an exception handler:

CODE

public class Main {
    public static void main(String[] args) {
        try {
			
			// Here, we create an integer array with three elements, and the fourth element (index 3) is accessed.
            int[] arr = {1, 2, 3};
            int x = arr[3];
        } catch (ArrayIndexOutOfBoundsException e) {
			
			// If an exception occurs, the catch block will be executed, printing an error message.
            System.out.println("Array index out of bounds: " + e.getMessage());
        }
    }
}

 

OUTPUT 

Output

In this illustration, we're attempting to access the element at index 3 of an array with only three other elements. As a result, an ArrayIndexOutOfBoundsException will be thrown. 

Comparison Table between Error and Exception

Here is a comparison table between Errors and Exceptions in Java:

Comparison Point Error Exception
Underlying Cause External factors like hardware malfunctions, resource depletion, or operating system issues frequently result in errors. Typically, errors in the code or input data, such as null references, division by zero, or invalid arguments, cause exceptions.
Throwing Instead of the application code, errors are typically thrown by the JVM or system libraries. The application code explicitly throws exceptions, frequently in response to particular input or processing conditions.
Class hierarchy Errors are subclasses of the java.lang.Error class. Exceptions are subclasses of the java.lang.Exception class.
Handling Typically, errors cannot be fixed, and they frequently lead to the application being closed. Exceptions can be handled correctly to recover from them and allow the application to keep running.
Examples

Examples of JVM errors include ClassCircularityError, IncompatibleClassChangeError, and NoClassDefFoundError. 

Examples of system errors include InternalError, UnknownError, and StackOverflowError.

Examples of checked exceptions include IOException, ClassNotFoundException, and SQLException. Examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, and IllegalArgumentException.

 

As of now, you might have gotten the idea of the difference between error and exception in Java. Now we move into the FAQ section.

Frequently Asked Questions

What is the difference between error and exception in Java?

Problems with hardware or operating system failures cause errors. The exceptions are caused by issues within the program itself, such as incorrect user input or network failures.

Can you describe the stack trace concept in exception handling?

The method calls that the application was in the middle of when an exception was thrown are listed in a stack trace. It can help developers identify the error's location and root cause.

In Java, how do you make your unique exception?

You can create a class in Java that extends the Exception class or one of its subclasses and include a constructor with a message to make a custom exception. Then, you can throw an instance whenever a custom exception is required.

What does the finally block in exception handling accomplish?

The finally block is used in exception handling to hold critical statements that must be carried out whether or not an exception occurs. It helps clean up resources allocated in the try block because it is executed regardless of whether an exception is thrown or caught.

What function does the try-catch block serve in handling exceptions?

The try-catch block's function in exception handling is to catch and deal with any exceptions that might arise in the try block. The code that might throw an exception is contained in the try block, and the catch block specifies how to handle the thrown exception. 

Conclusion

In conclusion, errors and exceptions are essential for locating and managing coding errors in Java programming. The definitions, distinctions, and types of errors and exceptions in Java have all been covered in this article. Practical error-handling strategies have also been covered, such as using try-catch blocks, creating notable exceptions, and relying on third-party libraries.

Below are some articles to deepen your knowledge and understanding of Java's error and exception handling. 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses, refer to the mock test and problems look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

Live masterclass