>  기사  >  Java  >  Java 예외에 대해 자세히 알아보기

Java 예외에 대해 자세히 알아보기

PHPz
PHPz원래의
2024-08-19 06:01:02459검색

Java 코어 예외 클래스

예외 클래스 계층: Throwable < 오류 < Throwable이 슈퍼클래스인 예외

던질 수 있는

Throwable 클래스는 Java 언어의 모든 오류와 예외의 상위 클래스입니다. 이 클래스(또는 해당 하위 클래스 중 하나)의 인스턴스인 객체만 Java Virtual Machine에 의해 던져지거나 Java throw 문에 의해 던져질 수 있습니다. 참고

실제로 Throwable은 일반적으로 개발자가 직접 사용하지 않습니다. 대신, 두 가지 직접적인 하위 클래스인 오류와 예외의 기반 역할을 합니다.

try {
 // some process
} catch (Throwable t) {
    throw new Throwable(t);
}

오류

오류는 합리적인 애플리케이션이 포착하려고 시도해서는 안 되는 심각한 문제를 나타내는 Throwable의 하위 클래스입니다. 오류는 일반적으로 JVM 자체 참조에서 발생하는 비정상적인 조건을 나타냅니다

비정상적인 상태는 문제가 일반적으로 애플리케이션 제어 범위를 벗어난 요인으로 인해 발생하며 일반적으로 복구할 수 없음을 의미합니다. 예 : OutOfMemoryError, StackOverflowError

Deep Dive into Java Exceptions

예외

예외란 프로그램 실행 중에 발생하는 예상치 못한 이벤트나 상황을 말하며, 이를 잡아야 합니다. 예외를 포착함으로써 예상치 못한 상황을 적절하게 처리하여 프로그램이 충돌하지 않도록 할 수 있습니다.

int[] arr = {1, 2, 3};
try {
    System.out.println(arr[3]); // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Unchecked Exception: " + e.getMessage());
}

 

예외 유형

자바에는 2가지 유형의 예외가 있습니다. 참고

확인된 예외

확인된 예외는 잘못될 수 있다는 것을 알고 있는 상황과 같으므로 이에 대한 계획을 세워야 합니다. try-catch 블록을 사용하여 포착하거나 throws 절을 사용하여 메서드 시그니처에서 선언해야 합니다. 메소드가 확인된 예외를 발생시킬 수 있는데 이를 처리하지 않으면 프로그램이 컴파일되지 않습니다.

// Checked exception
try {
    readFile("nonexistent.txt");
} catch (FileNotFoundException e) {
    System.out.println("Checked Exception: " + e.getMessage());
}
// Checked exception
public void getData() throws SQLException { // throw SQLException
    throw new SQLException("err");
}

확인되지 않은 예외

확인되지 않은 예외라고도 합니다. 런타임 예외는 Java 컴파일러에서 처리할 필요가 없는 예외입니다. 이는 RuntimeException의 하위 클래스입니다. 확인된 예외와 달리 이러한 예외는 메서드 시그니처에서 포착하거나 선언할 필요가 없습니다. 이는 일반적으로 논리 결함, API의 잘못된 사용 또는 코드의 가정 위반과 같은 프로그래밍 오류를 나타냅니다.

String text = null;
System.out.println(text.length()); // This will throw a NullPointerException

 

일반적인 유형의 Java 예외

NullPointerException: 애플리케이션이 초기화되지 않은 객체 참조를 사용하려고 할 때 발생합니다.

String text = null; // text is not initialized
try {
    System.out.println(text.length()); // Attempting to call length() on a null reference
} catch (NullPointerException e) {
    System.out.println("Caught a NullPointerException: " + e.getMessage());
}

ArrayIndexOutOfBoundsException: 잘못된 인덱스가 있는 배열에 액세스하려고 하면 발생합니다.

int[] numbers = {1, 2, 3};
try {
    int value = numbers[5]; // Attempting to access index 5, which is out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Caught an ArrayIndexOutOfBoundsException: " + e.getMessage());
}

IllegalArgumentException: 메소드가 부적절한 인수를 수신할 때 발생합니다.

public class IllegalArgumentExample {
    public static void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative"); // Illegal argument
        }
        System.out.println("Age set to: " + age);
    }

    public static void main(String[] args) {
        try {
            setAge(-5); // Passing a negative age, which is illegal
        } catch (IllegalArgumentException e) {
            System.out.println("Caught an IllegalArgumentException: " + e.getMessage());
        }
    }
}

 

예외를 처리하는 방법

시도-캐치

코드 블록 내에서 발생할 수 있는 특정 예외를 처리하려면 try-catch를 사용하세요

try {
    int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Caught an ArithmeticException: " + e.getMessage());
}

멀티캐치

유사한 방식으로 여러 예외 유형을 처리하려면 멀티 캐치를 사용하세요

try {
    String str = null;
    System.out.println(str.length()); // This will throw NullPointerException
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
    System.out.println("Caught an exception: " + e.getMessage());
}

리소스 활용

파일, 소켓, 데이터베이스 연결 등 사용 후 닫아야 하는 리소스로 작업할 때 try-with-resources를 사용하세요.

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    System.out.println("Caught an IOException: " + e.getMessage());
}

마지막으로

예외 발생 여부에 관계없이 특정 코드가 실행되도록 해야 할 때 finally 블록을 사용하세요

try {
    file = new FileReader("file.txt");
} catch (IOException e) {
    System.out.println("Caught an IOException: " + e.getMessage());
} finally {
    if (file != null) {
        file.close(); // Ensure the file is closed
    }
}

 

예외 처리 모범 사례

예외를 무시하지 마십시오: 예외는 단지 잡아서 무시하는 것이 아니라 적절하게 처리되어야 합니다.

try {
    file = new FileReader("file.txt");
} catch (IOException ignored) {
    // ignored
}

특정 예외 사용: 일반적인 예외를 사용하기보다는 특정 예외를 사용하세요.

try {
    // Code that may throw exceptions
    String text = null;
    text.length();
} catch (Exception e) {
    // Too broad; will catch all exceptions
    System.err.println("An error occurred: " + e.getMessage());
}

올바른 처리 방법:

try {
    // Code that may throw exceptions
    String text = null;
    text.length();
} catch (NullPointerException e) {
    // Handle specific exception
    System.err.println("Null pointer exception: " + e.getMessage());
} catch (Exception e) {
    // Handle other exceptions
    System.err.println("An error occurred: " + e.getMessage());
}

Clean Resource Handling: 메모리 누수를 방지하기 위해 항상 리소스를 닫습니다

FileReader fileReader = null;
try {
    fileReader = new FileReader("file.txt");
    // Read from the file
} catch (IOException e) {
    System.err.println("File not found: " + e.getMessage());
} finally {
   fileReader.close(); // clouse resources
}

사용자 정의 예외: 표준 예외가 특정 오류 조건에 적합하지 않은 경우 사용자 정의 예외를 생성합니다.

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

// Usage
public class Example {
    public void performOperation() throws CustomException {
        // Some condition
        throw new CustomException("Custom error message");
    }

    public static void main(String[] args) {
        Example example = new Example();
        try {
            example.performOperation();
        } catch (CustomException e) {
            System.err.println("Caught custom exception: " + e.getMessage());
        }
    }
}

로깅: 디버깅 및 유지 관리를 위한 예외를 기록합니다.

public class Example {
    private static final Logger logger = Logger.getLogger(Example.class.getName());

    public void riskyMethod() {
        try {
            // Code that may throw an exception
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            // Log the exception
            logger.severe("An arithmetic error occurred: " + e.getMessage());
        }
    }
}

예외 남용 방지: 흐름 제어를 위해 예외를 사용하지 않도록 경고합니다. 정말 예외적인 상황을 처리하는 데에만 사용해야 합니다.

public class Example {
    public void process(int[] array) {
        try {
            // Using exceptions to control flow
            if (array.length < 5) {
                throw new ArrayIndexOutOfBoundsException("Array too small");
            }
            // Process array
        } catch (ArrayIndexOutOfBoundsException e) {
            // Handle exception
            System.out.println("Handled array size issue.");
        }
    }
}

올바른 처리 방법:

public class Example {
    public void process(int[] array) {
        if (array.length >= 5) {
            // Process array
        } else {
            // Handle the condition without using exceptions
            System.out.println("Array is too small.");
        }
    }
}




 
어떤 피드백이라도 도움이 될 것입니다 :)

위 내용은 Java 예외에 대해 자세히 알아보기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.