Java Exception Handling

  1. Understanding Exceptions =======

In software development, developers aim to create robust and rleiable applications. Despite careful coding, unexpected issues can arise during runtime, such as incorrect data formats, network failures, or memory issues. A skilled developer must learn how to handle these exceptions effectively to ensure the program runs smoothly.

  1. Common Exceptions =======
    java.lang.RuntimeException: Runtime exception
    ClassCastException: Thrown when an object is not an instance of the expected class;
    ArrayIndexOutOfBoundsException: Thrown when accessing an array with an invalid index;
    NullPointerException: Thrown when trying to access a method or property of a null object;
    ArithmeticException: Thrown when an arithmetic operation fails, such as division by zero;
    NumberFormatException: Thrown when converting a string to a numeric type but the string is not in the correct format;
    InputMismatchException: Thrown when input values do not match the expected data types.


2.1 Java Exception Hierarchy:

As shown in the diagram:

  1. Throwable: The base class for all exceptions and errors.
  2. Error: Represents serious problems that a Java Virtual Machine (JVM) cannot handle, such as StackOverflowError or OutOfMemoryError.
  3. Exception: Indicates exceptions that can be handled in code, allowing the program to continue running.
  4. Types of Exceptions =======

3.1 Compile-Time Exceptions:

These are exceptions that occur during the coding phase, often indicated by red underlines in the IDE.

3.1.1 IOException

This occurs when there are issues with input/output operations, such as file not found or database connection failures.

3.1.2 FileNotFoundException

This exception occurs when a file is not found in the compiled output directory, not the source project folder.

3.1.3 ClassNotFoundException

This happens when a class cannot be found during class loading.

3.1.4 DataFormatException

3.1.5 NoSuchFieldException

3.1.6 NoSuchMethodException

3.1.7 SQLException

3.1.8 TimeoutException

3.2 Runtime Exceptions:

These are exceptions that occur during program execution.

ArrayIndexOutOfBoundsException
ClassCastException
NullPointerException
IllegalAccessException
InputMismatchException

  1. Handling Exceptions ==========

4.1 Proactive Approach

This involves checking conditions before performing actions, for example:

boolean result = false;
result = loginGame();
if (!result) {
    handleLoginError();
    return;
}
result = matchGame();
if (!result) {
    handleMatchError();
    return;
}
result = confirmGame();
if (!result) {
    handleConfirmError();
    return;
}


Advantages: Makes it easy to identify and fix issues quickly.
Disadvantages: Mixing error handling with normal flow can make the code messy and harder to read.


4.2 Reactive Approach

This involves executing code first and handling errors as they occur, for example:

try {
    loginGame();
    matchGame();
    confirmGame();
    selectHero();
    loadGameScene();
    ...
} catch (LoginException e) {
    handleLoginException(e);
} catch (MatchException e) {
    handleMatchException(e);
} catch (ConfirmException e) {
    handleConfirmException(e);
} catch (HeroSelectException e) {
    handleHeroSelectException(e);
} catch (LoadSceneException e) {
    handleLoadSceneException(e);
}


Advantages: Separates normal and error flows, making the code cleaner and easier to understand.
Disadvantages: Some exceptions need immediate handling, which may not be possible if all code is executed first.


Note: When catching multiple exceptions, child exceptions should come before parent exceptions to avoid errors.

  1. Throwing Exceptions ================

Sometimes, you may need to define custom exceptions. You can use the throw keyword to throw an exception object, informing the caller about the issue. The syntax is as follows:

throw new CustomException("Reason for the exception");


Example: Create a method to retrieve an element from an array.

public static int getElement(int[] arr, int idx){
    if(arr == null){
        throw new NullPointerException("Array is null");
    }
    if(idx < 0 || idx >= arr.length){
        throw new ArrayIndexOutOfBoundsException("Index out of bounds");
    }
    return arr[idx];
}
public static void main(String[] args) {
    int[] arr = {1,2,3};
    getElement(arr, 3);
}
 
Output:
Index out of bounds


【 Notes 】

  1. throw must be used inside a method body.
  2. The thrown object must be an instance of Exception or its subclass.
  3. If a RuntimeException or its subclass is thrown, no additional handling is required; the JVM handles it.
  4. Compile-time exceptions must be handled; otherwise, the code will not compile.
  5. Once an exception is thrown, the rest of the code after that point will not execute.

Tags: java exception-handling exceptions Try-Catch custom-exceptions

Posted on Sun, 17 May 2026 23:01:05 +0000 by funguse