A n is an object that is generated in memory as the result of an error or an unexpected event

Cause: The detail message Java heap space indicates object could not be allocated in the Java heap. This error does not necessarily imply a memory leak. The problem can be as simple as a configuration issue, where the specified heap size (or the default size, if it is not specified) is insufficient for the application.

In other cases, and in particular for a long-lived application, the message might be an indication that the application is unintentionally holding references to objects, and this prevents the objects from being garbage collected. This is the Java language equivalent of a memory leak. Note: The APIs that are called by an application could also be unintentionally holding object references.

One other potential source of this error arises with applications that make excessive use of finalizers. If a class has a finalize method, then objects of that type do not have their space reclaimed at garbage collection time. Instead, after garbage collection, the objects are queued for finalization, which occurs at a later time. In the Oracle Sun implementation, finalizers are executed by a daemon thread that services the finalization queue. If the finalizer thread cannot keep up, with the finalization queue, then the Java heap could fill up and this type of OutOfMemoryError exception would be thrown. One scenario that can cause this situation is when an application creates high-priority threads that cause the finalization queue to increase at a rate that is faster than the rate at which the finalizer thread is servicing that queue.

What is exception handling?

Exception handling is the process of responding to unwanted or unexpected events when a computer program runs. Exception handling deals with these events to avoid the program or system crashing, and without this process, exceptions would disrupt the normal operation of a program.

Exceptions occur for numerous reasons, including invalid user input, code errors, device failure, the loss of a network connection, insufficient memory to run an application, a memory conflict with another program, a program attempting to divide by zero or a user attempting to open files that are unavailable.

When an exception occurs, specialized programming language constructs, interrupt hardware mechanisms or operating system interprocess communication facilities handle the exception.

Exception handling differs from error handling in that the former involves conditions an application might catch versus serious problems an application might want to avoid. In contrast, error handling helps maintain the normal flow of software program execution.

How is exception handling used?

If a program has a lot of statements and an exception happens halfway through its execution, the statements after the exception do not execute, and the program crashes. Exception handling helps ensure this does not happen when an exception occurs.

A n is an object that is generated in memory as the result of an error or an unexpected event
The try block detects and throws any found exceptions to the catch blocks, which then handles them.

Exception handling can catch and throw exceptions. If a detecting function in a block of code cannot deal with an anomaly, the exception is thrown to a function that can handle the exception. A catch statement is a group of statements that handle the specific thrown exception. Catch parameters determine the specific type of exception that is thrown.

Exception handling is useful for dealing with exceptions that cannot be handled locally. Instead of showing an error status in the program, the exception handler transfers control to where the error can be handled. A function can throw exceptions or can choose to handle exceptions.

Error handling code can also be separated from normal code with the use of try blocks, which is code that is enclosed in curly braces or brackets that could cause an exception. Try blocks can help programmers to categorize exception objects.

A n is an object that is generated in memory as the result of an error or an unexpected event
The try bracket contains the code that encounters the exception and prevents the application from crashing.

What are the types of exceptions?

Exceptions can come in the following two exception classes:

  1. Checked exceptions. Also called compile-time exceptions, the compiler checks these exceptions during the compilation process to confirm if the exception is being handled by the programmer. If not, then a compilation error displays on the system. Checked exceptions include SQLException and ClassNotFoundException.
  2. Unchecked exceptions. Also called runtime exceptions, these exceptions occur during program execution. These exceptions are not checked at compile time, so the programmer is responsible for handling these exceptions. Unchecked exceptions do not give compilation errors. Examples of unchecked exceptions include NullPointerException and IllegalArgumentException.

Exception handling in Java vs. exception handling in C++

Although the try, throw and catch blocks are all the same in the Java and C++ programming languages, there are some basic differences in each language.

For example, C++ exception handling has a catch all block, which can catch different types of exceptions, but Java does not. Likewise, C++ is able to throw primitives and pointers as exceptions, but Java can only throw objects as exceptions.

Unlike C++, Java has both checked and unchecked exceptions. Java also has a finally clause, which executes after the try-catch block for cleanup. C++ does not have a finally block. However, the finalize method will be removed in future versions of Java, which means users will have to find different methods to handle Java errors and cleanup.

Examples of exception handling

The following are examples of exceptions:

  • SQLException is a checked exception that occurs while executing queries on a database for Structured Query Language syntax.
  • ClassNotFoundException is a checked exception that occurs when the required class is not found -- either due to a command-line error, a missing CLASS file or an issue with the classpath.
  • IllegalStateException is an unchecked exception that occurs when an environment's state does not match the operation being executed.
  • IllegalArgumentException is an unchecked exception that occurs when an incorrect argument is passed to a method.
  • NullPointerException is an unchecked exception that occurs when a user tries to access an object using a reference variable that is null or empty.

In this example, a variable is left undefined, so console.log generates an exception. The try bracket is used to contain the code that encounters the exception, so the application does not crash. The catch block is skipped if the code works. But, if an exception occurs, then the error is caught, and the catch block is executed.

Learn about the best practices behind exception handling for secure code design, including the process of throwing and handling different exceptions.

This was last updated in June 2022

Continue Reading About exception handling

  • Discover three key exploit protection features in Windows 10
  • A breakdown of object-oriented programming concepts
  • Learn 5 defensive programming techniques from experts
  • A comparison of 6 top programming languages
  • Fix the 5 most common types of runtime errors in Java

Dig Deeper on Software testing tools and techniques

  • A n is an object that is generated in memory as the result of an error or an unexpected event
    Java Exception handling best practices

    A n is an object that is generated in memory as the result of an error or an unexpected event

    By: Cameron McKenzie

  • A n is an object that is generated in memory as the result of an error or an unexpected event
    What are checked vs. unchecked exceptions in Java?

    A n is an object that is generated in memory as the result of an error or an unexpected event

    By: Cameron McKenzie

  • A n is an object that is generated in memory as the result of an error or an unexpected event
    Either log or rethrow Java exceptions, but never do both
  • A n is an object that is generated in memory as the result of an error or an unexpected event
    An example of how suppressed exceptions in Java work

    A n is an object that is generated in memory as the result of an error or an unexpected event

    By: Cameron McKenzie

What does it mean to catch an exception?

When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. The exception handler chosen is said to catch the exception.

What is the difference between exceptions that inherit from the error class and exceptions that inherit from the exception class?

What is the difference between exceptions that inherit from the Error class and exceptions that inherit from the Exception class? Error class does critical errors, internal errors in JVM, or no memory. Exception class does exceptions apps can handle.

When an exception is thrown by a method that is executing under several layers of method calls?

8) When an exception is thrown by a method that is executing under several layers of method calls, a stack trace indicates the method executing when an exception occurred and all of the methods that were called in order to execute that method.

When you write a method that throws a checked exception you must?

If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using the throws keyword. In checked exception, there are two types: fully checked and partially checked exceptions.