>  기사  >  Java  >  자바 예외 처리

자바 예외 처리

WBOY
WBOY원래의
2024-08-28 06:37:02388검색

Java Exception Handling

기본

예외 이해: 문제가 발생하면 어떻게 되나요?

게임을 하고 있는데 갑자기 캐릭터가 구덩이에 빠진다고 상상해 보세요. 당신은 무엇을 하시겠습니까? 아마도 게임을 다시 시작하거나 다음번에는 구덩이를 피할 방법을 찾을 것입니다. 프로그래밍에서도 비슷한 일이 발생할 수 있습니다. 코드가 예외라는 "구덩이"에 빠질 수 있습니다. 그런 일이 발생하면 프로그램이 작동을 멈추거나 예상치 못한 일이 발생할 수 있습니다.

예외란 정확히 무엇인가요?

예외는 코드가 실행되는 동안 문제가 발생했다는 신호와 같습니다. 숫자를 0으로 나누려고 했을 수도 있고(허용되지 않음) 존재하지 않는 파일을 열려고 했을 수도 있습니다. 이러한 문제가 발생하면 Java는 플래그를 세우고 "야! 여기에 문제가 생겼어!"라고 말합니다.

예외 처리를 하지 않으면 어떻게 되나요?

예외를 처리하지 않으면 게임이 저장되지 않아 컴퓨터가 갑자기 꺼지는 것처럼 프로그램이 충돌하고 모든 진행 상황이 손실될 수 있습니다.

예를 살펴보겠습니다.

public class BasicExample {
    public static void main(String[] args) {
        int number = 10;
        int result = number / 0; // This will cause an exception!
        System.out.println("Result: " + result); // This line will never be reached.
    }
}

이 코드를 실행하려고 하면 멈추면서 "0으로 나눌 수 없습니다!"라고 불평합니다.

어떻게 구덩이를 피할 수 있나요?

이 문제를 방지하기 위해 Java는 try and catch라는 기능을 제공합니다.

  • 차단 시도: 문제를 일으킬 수 있는 작업을 시도하는 곳입니다.
  • catch 블록: 문제가 발생하는 경우 이를 잡아 프로그램이 충돌하지 않도록 하는 곳입니다.

예제를 다시 작성해 보겠습니다.

public class BasicExample {
    public static void main(String[] args) {
        int number = 10;

        try {
            int result = number / 0; // We know this might cause a problem.
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Oops! You can’t divide by zero.");
        }
    }
}

현재 상황은 다음과 같습니다.

  • try 블록은 0으로 나누기를 시도합니다.
  • Java는 문제를 발견하면 catch 블록으로 점프하여 "앗! 0으로 나눌 수는 없습니다."라고 말합니다.

다양한 문제 포착

예외 포착에 대한 추가 정보

이제 예외를 포착하는 방법을 알았으니 "내 코드에 다양한 종류의 문제가 있으면 어떻게 하지? 어떻게 모두 포착할 수 있지?"라고 궁금하실 것입니다.

게임에서 보물 상자를 열려고 한다고 상상해 보세요. 때로는 열쇠가 맞지 않는 경우도 있고(이것이 하나의 문제임), 상자가 비어 있는 경우도 있습니다(이것은 다른 문제입니다). 정확히 무엇이 잘못되었는지 알고 싶으시죠?

다양한 예외 유형

Java에는 다양한 종류의 문제, 즉 예외가 있습니다. 예:

  • ArithmeticException: 0으로 나누기와 같이 말이 안 되는 계산을 하려고 할 때.
  • NullPointerException: 아직 존재하지 않는 것을 사용하려고 할 때(예: 존재하지 않는 보물 상자를 열려고 하는 경우)
  • ArrayIndexOutOfBoundsException: 10개만 들어 있는 병에 11번째 쿠키를 요청하는 것과 같이 한계를 넘어서는 항목에 대해 배열에 접근하려고 할 때.

여러 예외 잡기

코드에서 다양한 유형의 문제를 포착하는 방법을 살펴보겠습니다.

public class MultipleExceptionsExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]); // This will cause an ArrayIndexOutOfBoundsException!
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Oops! You tried to access an index that doesn’t exist.");
        } catch (ArithmeticException e) {
            System.out.println("Oops! You can’t divide by zero.");
        }
    }
}

상황은 다음과 같습니다.

  • try 블록의 코드가 문제를 일으킬 수 있는 작업을 시도합니다.
  • ArrayIndexOutOfBoundsException이 발생하면 첫 번째 catch 블록으로 점프합니다.
  • ArithmeticException이 발생하면 두 번째 catch 블록으로 점프합니다.

문제가 있으면 어떻게 하나요?

때로는 무엇이 잘못될지 알 수 없지만 여전히 문제를 파악하고 싶을 수도 있습니다. 일반적인 예외를 사용하여 잘못된 모든 것을 잡을 수 있습니다:

public class GeneralExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will cause an ArithmeticException!
        } catch (Exception e) {
            System.out.println("Oops! Something went wrong.");
        }
    }
}

이렇게 하면 문제가 발생하더라도 catch 블록이 이를 처리하고 프로그램이 충돌하지 않습니다.

사용자 정의 예외 정리 및 만들기

더 마지막 블록

게임을 하다가 보물을 찾았다고 상상해 보세요. 성공 여부에 관계없이 게임을 마친 후에는 항상 보물 상자를 닫고 싶어합니다. Java에서 finally 블록은 무슨 일이 있어도 보물 상자가 항상 닫혀 있는지 확인하는 것과 같습니다.

마지막 블록이 무엇인가요?

finally 블록은 예외 발생 여부에 관계없이 항상 실행되는 코드 조각입니다. 파일 닫기, 타이머 정지, 보물상자 정리 등을 정리하는 데 사용됩니다.

예를 살펴보겠습니다:

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will cause an exception.
        } catch (ArithmeticException e) {
            System.out.println("Oops! You can’t divide by zero.");
        } finally {
            System.out.println("This will always run, no matter what.");
        }
    }
}

상황은 다음과 같습니다.

  • The try block tries to do something risky.
  • The catch block catches the problem if it happens.
  • The finally block always runs, even if there’s no problem.

Making Your Own Custom Exceptions

Sometimes, the problems you face in your code are special. Maybe the game doesn’t just have treasure chests, but also magical doors that can sometimes be locked. You might want to create a special exception for when the door is locked.

Creating a Custom Exception

You can create your own exceptions by making a new class that extends Exception. Let’s create an exception called LockedDoorException:

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

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            openDoor(false);
        } catch (LockedDoorException e) {
            System.out.println(e.getMessage());
        }
    }

    private static void openDoor(boolean hasKey) throws LockedDoorException {
        if (!hasKey) {
            throw new LockedDoorException("The door is locked! You need a key.");
        }
        System.out.println("The door is open!");
    }
}

Here’s how it works:

  • We create a new exception called LockedDoorException.
  • When we try to open the door without a key, we throw the LockedDoorException.
  • The catch block catches our custom exception and tells us what went wrong.

Summary

In this post, we’ve learned that:

  • Exceptions are problems that happen when your code is running.
  • try and catch blocks help us handle these problems, so our program doesn’t crash.

  • Different types of exceptions are like different kinds of problems.

  • We can catch multiple exceptions to handle specific problems.

  • We can also catch any exception using the general Exception type.

  • The finally block is used to clean up, and it always runs no matter what.

  • You can create custom exceptions to handle special problems in your code.

And that it! Now you’re ready to handle any problem that comes your way in your code. If you have any questions, feel free to ask!

위 내용은 자바 예외 처리의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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