CodeGym/Java Blog/무작위의/Java는 여러 예외를 포착합니다.
John Squirrels
레벨 41
San Francisco

Java는 여러 예외를 포착합니다.

무작위의 그룹에 게시되었습니다
회원
여러 예외를 포착하는 방법을 배우기 전에 Java의 기본 예외 처리 에 대해 잘 알고 있어야 합니다 . 앞으로는 Java의 try 및 catch 블록에 익숙하다고 가정합니다.

Java에서 여러 catch 블록이 필요한 이유는 무엇입니까?

Java의 여러 catch 블록은 다양한 유형의 예외를 처리하는 데 사용됩니다. Java 7이 출시되기 전에 특정 예외를 포착하려면 특정 catch 블록이 필요했습니다. 이로 인해 중복 코드 블록이 생성되어 비효율적인 접근 방식이 되었습니다. 잡힌 예외를 확인하려면 다음 예를 살펴보십시오. 다른 종류의 예외에 대해 별도의 catch 블록을 사용합니다.

별도의 Catch 블록을 사용하는 예

import java.util.Arrays;

public class ExceptionHandler {

	public static void main(String[] args) {

		Integer[] colorsOfASpectrum = { 7, 6, 5, 4, 3, 2, 1, 0 };

		try {

			System.out.println("Total number of options on a dice are: " + Arrays.toString(colorsOfASpectrum));

	// 		un-comment the following line to see "Index Out of Bounds Exception"
	//		colorsOfASpectrum[10] = 7; // Index Out of Bounds Exception

			System.out.println(colorsOfASpectrum[0] / 0);	// Arithmetic Exception

		} catch (ArrayIndexOutOfBoundsException e) {
			// This catch block executes in case of "Index Out of Bounds Exception"
			System.out.println("Array Index Out Of Bounds Exception " + e);

		} catch (ArithmeticException e) {
			// This catch block executes in case of "Arithmetic Exception"
			System.out.println("Arithmetic Exception " + e);
		}

		System.out.println("\n----Rest of the code executes here----");
	}
}

산출

스펙트럼의 총 색상은 다음과 같습니다. [7, 6, 5, 4, 3, 2, 1] 예외 발생 java.lang.ArithmeticException: / by zero ----나머지 코드는 여기에서 실행됩니다----
보시다시피 위의 예에서 예외가 발생하면 다른 블록이 실행됩니다. 다른 유형의 예외를 포착하기 위해 동일한 코드 블록을 사용하여 여러 예외를 포착하는 보다 효율적인 방법이 있습니다. 다음 예를 살펴보십시오.

Java에서 다중 Catch 블록을 사용하는 예

import java.util.Arrays;

public class MultiExceptionHandler {

	public static void main(String[] args) {

		Integer[] colorsOfASpectrum = { 7, 6, 5, 4, 3, 2, 1 };

		try {

			System.out.println("Total colors on a spectrum are: " + Arrays.toString(colorsOfASpectrum));

	//		colorsOfASpectrum[10] = 7; // Index Out of Bounds Exception
			System.out.println(colorsOfASpectrum[0] / 0); // Arithmetic Exception

		} catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
			// We don't need two different catch blocks for different kinds of exceptions
			// Both exceptions will be handled using this multiple catch block

			System.out.println("Exception Encountered " + e);
		}
		System.out.println("\n----Rest of the code executes here----");
	}
}

산출

다른 종류의 예외를 출력하기 위해 13행의 주석을 해제할 수 있습니다.
스펙트럼의 총 색상은 다음과 같습니다. [7, 6, 5, 4, 3, 2, 1] 예외 발생 java.lang.ArithmeticException: / by zero ----나머지 코드는 여기에서 실행됩니다----

결론

이것은 java catch multiple exceptions 블록 사용에 대한 빠른 개요였습니다. 문제로 부모와 자식 예외를 같은 블록에 인쇄해 보십시오. 성장을 위해 배우고 연습하는 것이 좋습니다. 건배와 행복한 학습!
코멘트
  • 인기
  • 신규
  • 이전
코멘트를 남기려면 로그인 해야 합니다
이 페이지에는 아직 코멘트가 없습니다