무룩 공부방

[Java02] 28. 예외(exception) 처리 (Eclipse) 본문

IT/Java02_Intermediate

[Java02] 28. 예외(exception) 처리 (Eclipse)

moo_look 2023. 10. 15. 16:53

# 예외(Exception)

  • 프로그램 코드에 의해서 수습될 수 있는 다소 미약한 오류로, 프로그램 실행시 발생할 수 있는 예외 발생에 대비해 코드를 작성하는 것
  • 예외처리 목적은 프로그램의 비 정상 종료를 막고, 정상적인 실행 상태를 유지하는 것
  • 모든 예외의 최고 조상은 Exceotion 클래스

 

# 예외의 종류

  • 존재하지 않는 파일의 이름을 입력 했을 때 - FileNotFoundException
  • 실수로 클래스 이름을 잘못 적었을 때 - ClassNotFoundException
  • 입력한 데이터 형식이 잘못 되었을 때 - DataFormatException
  • 배열의 범위를 벗어났을 때 - arrayIndexOutOfBoundsException
  • 값이 Null인 참조변수의 멤버를 호출 했을 때 - NullPointException
  • 클래스간의 형변환을 잘못 했을 때 - ClassCastException
  • 정수를 0으로 나누려고 했을 때 - ArithmeticException
  • 메모리가 부족할 때 - OutOfMemoryError
  • 잘못된 인자 전달 시 - IllegalArgumentException
  • 타입이 일치하지 않을 때 - InputMismatchException

주로 마주하는 예외는 위와 같이 있고 수 많은 예외들이 존재한다. 

 

 

# 예외처리 방법

try - catch - final
throws (추후 학습)

 

# try - catch - final

try {

	예외가 발생할 수 있는 문장

} catch(Exception e) {					 // Exception에 처리할 예외를 넣지만
							// Exception의 경우 모든 예외를 처리한다
  	  예외가 발생할 경우 실행할 문장

} finally {

	예외가 발생 여부와 관계없이 무조건 실행되는 문장
  	  (finally는 생략 가능하다)
    
}

package java02_intermediate;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Java28_예외처리 {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		int a;
		int b;
		
		System.out.print("a와 b값을 입력 : ");
		a = sc.nextInt();
		b = sc.nextInt();
		
		try {
			System.out.println(a / b);
			
		} catch(ArithmeticException e) { 
			System.out.println("0으로 나눌 수 없어요! 다시 입력하세요.");
			
		} finally {

		}
		
		//////////////////
		
		try {
			int[] arr = new int[5];
			arr[0] = 0;
			
			for(int i = 0; i < arr.length; i++) {
				arr[i+1] = i+1+arr[i];
			}
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("배열의 인덱스 범위를 벗어났습니다.");
		} finally {
			
		}
		
		int[] arr1 = new int[5];
		int c = 10;
		int d = 0;
		
		try {
			for(int i = 0; i < arr1.length; i++) {
				arr1[i] = i+1+arr1[i];
			}
			System.out.println(c / d);  
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("배열의 인덱스 범위를 벗어났습니다.");
		} catch (ArithmeticException e) {
			System.out.println("0으로 나눌 수 없어요! 다시 입력하세요.");
		} finally {
			
		}
		
		/////////////
		try {
			System.out.print("반드시 정수 입력 : ");
			int n = sc.nextInt();
			
		} catch (InputMismatchException e) {
			System.out.println("정수만 다시 입력하세요");
			
		} finally {
			
		}
		
		System.out.println("정수 입력 : ");
		try {
			int it = sc.nextInt();
		} catch (Exception e) {
			System.out.println("어떤 예외든 처리");
		}
		
	}

}