Popular Searches
Popular Course Categories
Popular Courses

Introduction to Errors and Exceptions in Java

Introduction to Errors and Exceptions in Java

Exception Handling and Debugging

Introduction to Errors and Exceptions in Java

Course: Core Java Training

Topic: Introduction to Errors and Exceptions in Java

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to Errors and Exceptions

Errors and exceptions are important concepts in Java programming. They describe problems or unexpected conditions that can interrupt the normal execution of a program. Understanding them helps developers write reliable, maintainable, and robust applications.

For example, a program may attempt to divide an integer by zero, access an array element that does not exist, open a file that is unavailable, or use a reference that contains null. Java provides an exception-handling mechanism to identify many such conditions and respond appropriately.

Java also distinguishes exceptions from serious errors that affect the Java Virtual Machine or the runtime environment. These categories belong to the Throwable class hierarchy.

Example: An Unhandled Exception

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;

        int result = a / b;

        System.out.println("Result: " + result);
        System.out.println("Program completed");
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

The division operation throws an ArithmeticException. Because the exception is not handled, the remaining statements in the method are not executed.

2. Learning Objectives

After completing this topic, you should be able to:

  • Understand errors and exceptions in Java.
  • Differentiate compilation errors, runtime exceptions, and logical errors.
  • Explain the Java Throwable class hierarchy.
  • Identify checked and unchecked exceptions.
  • Recognize common Java exceptions and errors.
  • Understand the purpose of try, catch, finally, throw, and throws.
  • Write basic exception-handling code.
  • Apply appropriate error-handling practices in real-world applications.

3. What Is an Error in Programming?

An error is a problem that causes a program to behave incorrectly or prevents it from executing as expected. Errors can occur at different stages of software development and execution.

Types of Programming Errors

Type Description Example
Syntax or compilation error A violation of Java syntax or compile-time rules prevents successful compilation. Missing semicolon or undeclared variable
Runtime exception A problem occurs while the program is executing and an exception is thrown. Dividing an integer by zero
Logical error The program runs but produces an incorrect result. Using addition instead of multiplication in a formula
Java Error A serious condition represented by a subclass of java.lang.Error. OutOfMemoryError

Example of a Syntax Error

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello Java")
    }
}

The statement is missing a semicolon. The compiler reports a compilation error, and the program cannot run until the code is corrected.

Example of a Logical Error

public class Main {
    public static void main(String[] args) {
        int length = 5;
        int width = 4;

        int area = length + width;

        System.out.println("Area: " + area);
    }
}

Output:

Area: 9

The program compiles and runs, but the area calculation is incorrect. The correct formula for a rectangle is length * width, which produces 20.

4. What Is an Exception in Java?

An exception is an object that represents an abnormal condition encountered during program execution. When an exception is thrown, Java interrupts the normal execution path and searches for an appropriate exception handler.

Exceptions may be generated by the Java Virtual Machine, Java library methods, or application code using the throw statement.

Real-World Examples of Exceptions

  • Dividing an integer by zero.
  • Accessing an array index outside its valid range.
  • Parsing invalid text as a number.
  • Attempting to use a method through a null reference.
  • Opening a file that does not exist.
  • Connecting to an unavailable service.

Example: Handling an Exception

public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide an integer by zero.");
        }

        System.out.println("Program continues.");
    }
}

Output:

Cannot divide an integer by zero.
Program continues.

The try block contains code that may throw an exception. The catch block handles the matching exception, allowing execution to continue after the exception-handling statement.

5. Understanding the Throwable Class Hierarchy

In Java, Throwable is the root class for objects that can be thrown and caught. It has two main direct subclasses: Error and Exception.

Object
  |
  +-- Throwable
       |
       +-- Error
       |    +-- OutOfMemoryError
       |    +-- StackOverflowError
       |    +-- LinkageError
       |
       +-- Exception
            |
            +-- RuntimeException
            |    +-- ArithmeticException
            |    +-- NullPointerException
            |    +-- ArrayIndexOutOfBoundsException
            |    +-- NumberFormatException
            |
            +-- Other checked exceptions
                 +-- IOException
                 +-- SQLException
                 +-- ClassNotFoundException

This hierarchy is simplified and shows representative subclasses rather than every class in the Java API.

Important Classes

Class Description
Throwable Base class for Java errors and exceptions that can be thrown.
Error Represents serious conditions that applications generally should not attempt to handle as ordinary recoverable problems.
Exception Represents conditions that an application may be able to handle.
RuntimeException Base class for unchecked exceptions that commonly indicate invalid operations or programming mistakes.
IOException Represents input/output-related problems.
ArithmeticException Represents certain invalid arithmetic operations, such as integer division by zero.

6. Difference Between Error and Exception

Although both Error and Exception extend Throwable, they serve different purposes.

Feature Error Exception
Meaning Serious runtime or environment-related condition Condition that an application may be able to handle
Typical cause Resource exhaustion or JVM-related problems Invalid input, missing files, or inappropriate operations
Recovery Often difficult or unsafe to recover from May be recoverable through validation, retry, or fallback logic
Handling approach Usually diagnose the underlying cause rather than catch routinely Catch or declare when appropriate
Examples OutOfMemoryError, StackOverflowError IOException, ArithmeticException

Important: An Error is not the same thing as a compilation error or logical error. A compilation error is detected by the compiler, while java.lang.Error is a specific class in Java's throwable hierarchy.

7. Checked Exceptions in Java

Checked exceptions are exceptions that the compiler requires a method to handle or declare when they can propagate beyond the method or constructor. They generally represent conditions that an application may need to anticipate and respond to.

Common Checked Exceptions

Exception Description
IOException Input/output operation fails.
FileNotFoundException A requested file cannot be found or opened.
SQLException A database access or SQL-related problem occurs.
ClassNotFoundException An application attempts to load a class by name but cannot find its definition.
InterruptedException A waiting or blocking operation is interrupted.

Example: Handling a Checked Exception

import java.io.FileReader;
import java.io.IOException;

public class FileExample {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("sample.txt");
            reader.close();
            System.out.println("File opened successfully.");
        } catch (IOException e) {
            System.out.println("Unable to read the file.");
        }
    }
}

The file may not exist or may not be accessible. The program handles the possible IOException instead of allowing it to propagate uncaught.

8. Unchecked Exceptions in Java

Unchecked exceptions include subclasses of RuntimeException. The compiler does not require these exceptions to be caught or declared with throws. They often indicate invalid operations, incorrect assumptions, or invalid data encountered during execution.

Common Unchecked Exceptions

Exception Cause Prevention
ArithmeticException Invalid integer arithmetic, such as division by zero. Validate the divisor.
NullPointerException Dereferencing a null reference. Validate references and design null handling carefully.
ArrayIndexOutOfBoundsException Using an array index outside its valid range. Check the index against array bounds.
NumberFormatException Parsing text that is not a valid number. Validate input and handle parsing failures.
IllegalArgumentException Passing an inappropriate argument to a method. Validate method arguments.
ClassCastException Attempting an incompatible reference type cast. Use appropriate types and check before casting when necessary.

Example: NumberFormatException

public class NumberExample {
    public static void main(String[] args) {
        String value = "abc";

        try {
            int number = Integer.parseInt(value);
            System.out.println(number);
        } catch (NumberFormatException e) {
            System.out.println("Please enter a valid integer.");
        }
    }
}

Output:

Please enter a valid integer.

9. Difference Between Checked and Unchecked Exceptions

Feature Checked Exception Unchecked Exception
Compiler enforcement Must be caught or declared when it can propagate out of a method No catch-or-declare requirement
Class hierarchy Subclass of Exception that is not a subclass of RuntimeException Subclass of RuntimeException
Typical examples IOException, SQLException NullPointerException, ArithmeticException
Common approach Handle or declare the expected failure Prevent invalid operations and handle where recovery is useful

10. Introduction to Exception Handling Keywords

Java provides several keywords and constructs for handling exceptional situations. These include try, catch, finally, throw, and throws.

10.1 The try Block

The try block contains statements that may throw exceptions. It must be followed by at least one catch block or a finally block, or both.

try {
    int result = 10 / 2;
    System.out.println(result);
} catch (ArithmeticException e) {
    System.out.println("Arithmetic problem occurred.");
}

10.2 The catch Block

The catch block defines how to respond when an exception matching its type is thrown from the associated try block.

try {
    int number = Integer.parseInt("hello");
} catch (NumberFormatException e) {
    System.out.println("Invalid numeric input.");
}

10.3 The finally Block

The finally block is used for cleanup actions. It normally executes whether the try block completes normally or an exception is thrown, even when a matching catch handles the exception.

try {
    System.out.println("Processing data.");
} catch (Exception e) {
    System.out.println("An exception occurred.");
} finally {
    System.out.println("Cleanup step completed.");
}

Note: The finally block is not an absolute guarantee under every circumstance, such as abrupt JVM termination. For resources implementing AutoCloseable, prefer try-with-resources where suitable.

10.4 The throw Keyword

The throw keyword explicitly throws a throwable object. It is useful when a program detects an invalid condition that should be reported to the caller.

public class AgeCheck {
    static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age must be 18 or above.");
        }

        System.out.println("Access granted.");
    }

    public static void main(String[] args) {
        checkAge(20);
    }
}

Output:

Access granted.

If the method is called with an age below 18, it throws an IllegalArgumentException.

10.5 The throws Keyword

The throws keyword appears in a method declaration to identify exceptions that may propagate to the caller. It is commonly used when a method allows the caller to handle a checked exception.

import java.io.FileReader;
import java.io.IOException;

public class FileExample {
    static void openFile() throws IOException {
        FileReader reader = new FileReader("sample.txt");
        reader.close();
    }

    public static void main(String[] args) {
        try {
            openFile();
        } catch (IOException e) {
            System.out.println("File operation failed.");
        }
    }
}

11. Difference Between throw and throws

Feature throw throws
Purpose Explicitly throws an exception object. Declares exception types that may propagate from a method or constructor.
Location Inside a method, constructor, or block. In a method or constructor declaration.
Followed by A throwable object. One or more exception types.
Example throw new IllegalArgumentException("Invalid"); void read() throws IOException

12. Multiple catch Blocks

A single try block can be followed by multiple catch blocks to handle different exception types separately. More specific exception types must appear before broader types that would otherwise catch them first.

public class MultipleCatchDemo {
    public static void main(String[] args) {
        try {
            String text = "abc";
            int number = Integer.parseInt(text);
            System.out.println(100 / number);
        } catch (NumberFormatException e) {
            System.out.println("The text is not a valid integer.");
        } catch (ArithmeticException e) {
            System.out.println("Division by zero is not allowed.");
        } catch (Exception e) {
            System.out.println("An unexpected exception occurred.");
        }
    }
}

Output:

The text is not a valid integer.

The final catch (Exception e) is broader than the previous catches. It must appear after the more specific exception handlers.

13. Common Java Errors

Java's Error class represents serious conditions that ordinary applications generally should not try to recover from through routine exception handling.

13.1 OutOfMemoryError

OutOfMemoryError may occur when the Java Virtual Machine cannot allocate more memory for an object and garbage collection cannot free enough space.

// Conceptual example only.
// Repeatedly allocating large objects without releasing references
// can exhaust available heap memory.

Prevention and diagnosis:

  • Investigate memory usage and object retention.
  • Avoid unnecessarily retaining large collections or objects.
  • Use profiling and heap dumps to diagnose memory problems.
  • Review memory configuration only after understanding the application's requirements.

13.2 StackOverflowError

StackOverflowError may occur when a thread's call stack becomes exhausted, often because of infinite or excessively deep recursion.

public class StackExample {
    static void repeat() {
        repeat();
    }

    public static void main(String[] args) {
        repeat();
    }
}

This program repeatedly calls repeat() without a stopping condition and can cause a StackOverflowError.

Prevention: Ensure recursive methods have correct base cases. Use iteration when it is more appropriate than deep recursion.

13.3 LinkageError

LinkageError represents problems that occur while linking classes, such as certain incompatible class definitions or missing dependencies at runtime.

Prevention: Keep dependencies compatible, use consistent build configurations, and verify that the expected classes and libraries are available at runtime.

14. Exception Propagation

Exception propagation occurs when a method does not handle an exception and the exception moves back through the call stack until a suitable handler is found. If no matching handler is found, the exception becomes uncaught for that thread.

Example

public class PropagationDemo {
    static void methodA() {
        int result = 10 / 0;
    }

    static void methodB() {
        methodA();
    }

    public static void main(String[] args) {
        try {
            methodB();
        } catch (ArithmeticException e) {
            System.out.println("Exception handled in main.");
        }
    }
}

Output:

Exception handled in main.

The exception originates in methodA(), passes through methodB(), and is handled in main().

15. Try-with-Resources

Try-with-resources is a Java language feature that automatically closes resources implementing AutoCloseable when the statement completes. It is commonly used with files, streams, and database resources.

Example

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ResourceDemo {
    public static void main(String[] args) {
        try (BufferedReader reader =
                 new BufferedReader(new FileReader("sample.txt"))) {
            System.out.println(reader.readLine());
        } catch (IOException e) {
            System.out.println("Unable to read the file.");
        }
    }
}

The reader is automatically closed when execution leaves the try-with-resources statement, including when an exception occurs during the operation.

16. Creating Custom Exceptions

Java allows developers to create custom exception classes to represent application-specific problems. For example, a banking application might define an exception for an invalid withdrawal amount.

Example: Custom Checked Exception

class InvalidAmountException extends Exception {
    public InvalidAmountException(String message) {
        super(message);
    }
}

public class BankAccount {
    static void withdraw(double amount) throws InvalidAmountException {
        if (amount <= 0) {
            throw new InvalidAmountException(
                "Withdrawal amount must be positive."
            );
        }

        System.out.println("Withdrawal request accepted.");
    }

    public static void main(String[] args) {
        try {
            withdraw(-100);
        } catch (InvalidAmountException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output:

Withdrawal amount must be positive.

Because InvalidAmountException extends Exception directly, it is a checked exception. A custom unchecked exception can instead extend RuntimeException.

17. Best Practices for Exception Handling

  • Catch exceptions that you can handle meaningfully.
  • Use specific exception types instead of catching Exception everywhere.
  • Do not silently ignore exceptions with empty catch blocks.
  • Provide useful, clear error messages without exposing passwords, secrets, or sensitive data.
  • Use try-with-resources for resources that implement AutoCloseable.
  • Do not use exceptions as the normal way to control routine program flow.
  • Validate input before performing operations that require specific values.
  • Preserve the original cause when wrapping an exception in another exception.
  • Avoid catching Error unless there is a specific, well-justified reason.
  • Use logging when appropriate so that failures can be diagnosed in real applications.
  • Restore the thread's interrupt status when catching InterruptedException if the interruption cannot be propagated.

18. Common Mistakes and Troubleshooting

Mistake Why It Is a Problem Better Approach
Catching every exception without distinction Hides the actual cause and makes recovery difficult. Catch specific exception types and respond appropriately.
Using an empty catch block Failures may go unnoticed. Handle the failure or log useful diagnostic information.
Confusing Error with a compilation error They refer to different concepts. Distinguish compiler diagnostics from java.lang.Error.
Placing a broad catch before a specific catch The specific catch becomes unreachable. Place more specific exception handlers first.
Throwing exceptions without useful messages Diagnosis becomes more difficult. Include meaningful context in the exception message.
Forgetting to close a resource Files or other resources may remain open. Use try-with-resources where possible.
Using exceptions for ordinary conditions Code becomes harder to understand and may be inefficient. Use normal condition checks for expected, routine cases.
Ignoring an interrupted thread Cancellation or shutdown signals may be lost. Propagate InterruptedException or restore the interrupt status when appropriate.

19. Practice Exercises

  1. Division Program: Write a program that divides two integers and handles ArithmeticException.
  2. Number Parsing: Convert a string to an integer and handle invalid numeric input.
  3. Array Access: Create an array and safely handle an invalid index.
  4. File Handling: Read a file using try-with-resources and handle an IOException.
  5. Multiple Catch Blocks: Write a program that handles both NumberFormatException and ArithmeticException.
  6. Exception Propagation: Create three methods and handle an exception in the calling method.
  7. Custom Exception: Create an InvalidAgeException for an age validation program.
  8. Finally Block: Demonstrate that a cleanup statement normally runs after a handled exception.
  9. Input Validation: Accept a positive number and reject invalid or negative values.

20. Mini Project: Student Marks Validator

Objective: Create a Java program that accepts student marks, validates the input, and handles invalid values using exception handling.

Project Requirements

  • Accept marks as text input.
  • Convert the text into an integer.
  • Handle invalid numeric input.
  • Check that marks fall between 0 and 100.
  • Throw an appropriate exception for out-of-range marks.
  • Display a meaningful success or error message.

Sample Implementation

import java.util.Scanner;

public class StudentMarksValidator {
    static void validateMarks(int marks) {
        if (marks < 0 || marks > 100) {
            throw new IllegalArgumentException(
                "Marks must be between 0 and 100."
            );
        }
    }

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Enter marks: ");
            String input = scanner.nextLine();

            try {
                int marks = Integer.parseInt(input);
                validateMarks(marks);

                System.out.println("Valid marks: " + marks);
            } catch (NumberFormatException e) {
                System.out.println("Please enter a whole number.");
            } catch (IllegalArgumentException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}

Sample Input:

Enter marks: 85

Output:

Valid marks: 85

If the user enters text such as hello, the program displays a numeric-input message. If the user enters a number outside the range 0 to 100, it displays the validation message.

21. Interview Questions and Answers

Q1. What is an exception in Java?

Answer: An exception is an object that signals an abnormal condition during program execution and interrupts the normal execution path.

Q2. What is the difference between Error and Exception?

Answer: An Error generally represents a serious runtime or environment-related condition. An Exception represents a condition that an application may be able to handle.

Q3. What is the Throwable class?

Answer: It is the root class of Java's throwable hierarchy. Both Error and Exception extend Throwable.

Q4. What is a checked exception?

Answer: It is an exception other than RuntimeException and its subclasses for which Java enforces a catch-or-declare requirement when it can propagate out of a method or constructor.

Q5. What is an unchecked exception?

Answer: An unchecked exception is a subclass of RuntimeException. The compiler does not require it to be caught or declared.

Q6. What is the purpose of try and catch?

Answer: The try block contains code that may throw an exception, while the catch block handles a matching exception.

Q7. What is the purpose of finally?

Answer: The finally block is commonly used for cleanup code that should normally execute whether the try block completes normally or exceptionally.

Q8. What is the difference between throw and throws?

Answer: throw explicitly throws an exception object. throws declares exception types that a method or constructor may allow to propagate.

Q9. What is exception propagation?

Answer: It is the process by which an exception moves up the call stack until a matching handler is found or the exception remains uncaught.

Q10. What is a custom exception?

Answer: It is a programmer-defined exception class that represents a specific application condition.

Q11. What is try-with-resources?

Answer: It is a Java construct that automatically closes resources implementing AutoCloseable when the statement finishes.

Q12. Should developers catch Error?

Answer: Usually not as part of ordinary application recovery. Errors often indicate serious conditions that require diagnosis, and catching them does not necessarily restore a safe application state.

22. Quick Revision Checklist

  • Understand the difference between syntax, logical, and runtime problems.
  • Know that Throwable is the root of the exception hierarchy.
  • Remember that Error and Exception are direct subclasses of Throwable.
  • Distinguish checked exceptions from unchecked exceptions.
  • Practice using try, catch, and finally.
  • Understand the difference between throw and throws.
  • Recognize common exceptions such as NullPointerException and NumberFormatException.
  • Know why try-with-resources is useful.
  • Understand exception propagation and custom exceptions.
  • Follow good practices for logging, cleanup, and input validation.

23. Conclusion

Errors and exceptions are fundamental to writing reliable Java applications. Understanding the difference between compilation problems, logical errors, runtime exceptions, and serious Java errors helps developers diagnose failures and choose the right response.

Java's exception-handling mechanism provides tools such as try, catch, finally, throw, and throws to manage exceptional conditions. By using these constructs carefully, validating input, cleaning up resources, and designing meaningful custom exceptions, developers can build applications that are easier to maintain and troubleshoot.

Continue Learning: Explore the Core Java Training Course, register for a course demo, or visit the JustAcademy website.

Previous Next
whatsapp