SoFunction
Updated on 2025-04-25

A detailed explanation of what you know about Java exception handling

Preface

In Java programming, exception handling is a crucial concept. By handling exceptions correctly, programmers can write robust and easy-to-maintain code to improve program reliability. This article will introduce Java's exception handling mechanism in detail, including exception classification, syntax for catching and handling exceptions, common exception types, and custom exception implementation.

1. What is an exception

Exceptions are errors or unexpected situations that occur during the program operation. Java uses exception mechanisms to handle these errors and accidents, allowing the program to recover from the errors or at least terminate safely.

2. Classification of exceptions

Exceptions in Java are divided into two categories: Checked Exception and Unchecked Exception.

2.1 Checked exception

The detected exception is an exception that needs to be handled at compile time. This means that at compile time, the compiler checks whether these exceptions are caught or declared. All directly inherited fromclass, but not inherited fromThe exceptions are all detected exceptions.

Example:

import ;
import ;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("");
        } catch (IOException e) {
            ();
        }
    }
}

2.2 Unchecked exceptions

Unchecked exceptions refer to exceptions that do not need to be explicitly processed at compile time. These exceptions include all inherited fromexception. Common non-tested exceptions includeNullPointerExceptionArrayIndexOutOfBoundsExceptionwait.

Example:

public class UncheckedExceptionExample {
    public static void main(String[] args) {
        int[] array = new int[5];
        (array[10]);  // Will cause ArrayIndexOutOfBoundsException    }
}

3. Syntax of exception handling

Java usagetry-catchblock to catch and handle exceptions. In addition, it can also be usedfinallyThe block performs some cleaning operations, whether or not the exception is thrown.

3.1 try-catch

try-catchBlocks are used to catch and handle exceptions. IftryAn exception is thrown in the block, and the program control will be transferred to the correspondingcatchpiece.

Example:

public class TryCatchExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            ("ArithmeticException caught: " + ());
        }
    }
}

3.2 try-catch-finally

finallyBlocks are used to perform some cleaning operations after exception handling, whether or not the exception is thrown.

Example:

public class TryCatchFinallyExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            ("ArithmeticException caught: " + ());
        } finally {
            ("This block is always executed.");
        }
    }
}

3.3 Multiple catch blocks

onetryThere can be multiple blockscatchblocks, eachcatchBlocks handle different types of exceptions.

Example:

public class MultipleCatchExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            ("ArithmeticException caught: " + ());
        } catch (Exception e) {
            ("Exception caught: " + ());
        }
    }
}

4. Common exception types

There are many common exception types in Java, and understanding these exceptions can help better handle and debug code.

4.1 NullPointerException

When a program tries to call a method or access its field on an empty object, it will be thrownNullPointerException

Example:

public class NullPointerExceptionExample {
    public static void main(String[] args) {
        String str = null;
        (());  // Will cause NullPointerException    }
}

4.2 ArrayIndexOutOfBoundsException

When the program tries to access an index that does not exist in the array, it will be thrownArrayIndexOutOfBoundsException

Example:

public class ArrayIndexOutOfBoundsExceptionExample {
    public static void main(String[] args) {
        int[] array = new int[5];
        (array[10]);  // Will cause ArrayIndexOutOfBoundsException    }
}

4.3 IOException

When an input/output operation fails or interrupts occur, it will be thrownIOException

Example:

import ;
import ;

public class IOExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("");
        } catch (IOException e) {
            ();
        }
    }
}

5. Custom exceptions

In some cases, the built-in exception type does not meet the needs, and a custom exception can be created at this time. Custom exceptions need to be inherited fromExceptionorRuntimeExceptionkind.

5.1 Create a custom exception

Example:

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

5.2 Using custom exceptions

Example:

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            validateAge(15);
        } catch (CustomException e) {
            ("CustomException caught: " + ());
        }
    }

    public static void validateAge(int age) throws CustomException {
        if (age < 18) {
            throw new CustomException("Age must be 18 or above");
        }
    }
}

6. Summary

Exception handling is an important part of Java programming. Through reasonable exception handling, the robustness and maintainability of the program can be improved. This article introduces the classification of exceptions in Java, the syntax for catching and handling exceptions, common exception types, and how to create and use custom exceptions. Mastering this knowledge can help you write more robust Java programs.

This is all about this article about Java exception handling. For more related Java exception handling content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!