[Java] 예외 및 예외처리

수경·2023년 8월 10일
0
post-thumbnail

예외, Exception

  • 런타임 오류
  • 컴파일 때 발견되지않고, 실행 중 발견되는 오류
  • 개발자가 경험을 통해 미리 예측 가능한 것도 있지만 예측 불가능한 것도 있다.
  • ex) n을 0으로 나누는 코드 (예측 가능함)




예외 처리, Exception Handing

  1. 전통적인 방식
  • 제어문 사용(조건문)
  1. 전용 방식
  • try catch finally 문 사용


try catch finally

	int num = 10;
    try {
		//비즈니스 영역
		System.out.println(100/num);
		
	} catch (Exception e) {
		//예외처리 영역
		System.out.println("예외 처리");
		
	} finally {
		//마무리 영역 : 에외와 상관없이 무조건 실행되는 블럭 
		System.out.println("마지막");
	}

에러 종류에 따른 예외처리

		//1. 0으로 나누기 오류
		//java.lang.ArithmeticException > 산술 연산 오류
		try {
			int num =0;
			System.out.println(100/num);
			
		} catch (Exception e) {
			System.out.println("0으로 나누려고 함");
		}
		
		
		//2. 배열 첨자
		//java.lang.ArrayIndexOutOfBoundsException
		try {
			int[] nums = new int[3];
			nums[5] = 10;
			
		} catch (Exception e) {
			System.out.println("배열 첨자 오류");
		}
		
		//3. 널 참조
		//java.lang.NullPointerException
		try {
			Scanner scan = null;
			scan.nextLine();
		} catch (Exception e) {
			System.out.println("널 참조 오류");
		}

다중 catch 문

		try {
			//0으로 나누기 오류
			int num = 10;
			System.out.println(100 / num);	// throw new ArithmeticException() > 에러 객체 생성 > 해당 catch 문에서 에러 객체를 잡는다.
			
			//배열 첨자
			int[] nums = new int[3];
			nums[0] = 10;
			
			//널 참조
			Scanner scan = null;
			scan.nextLine();
			
			//설정하지 않은 StringIndexOutOfBoundException 발생 > (Exception이 없다면)프로그램 중단
			
		}  catch (ArithmeticException e) {
			System.out.println("0으로 나누려고 함");
		
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("배열 첨자 오류");
		
		} catch (NullPointerException e) {
			System.out.println("널 참조 오류");
		
		} catch (Exception e) {		// else 절과 비슷함, 순서 주의
			System.out.println("예외 처리");
		}

예외 미루기, throws Exception

  • 예외 미루기 : 메소드 명 뒤에 throws Exception 붙이기
  • 해당 메소드에서 책임을 안지겠다는 뜻
  • 메인 메소드에서 사용하면 뒤로 미룰 메소드가 없어 에러시 프로그램이 뻑이 난다.
	private static void m5() throws Exception {
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		
		//Unhandled exception type IOException > 반드시는 아니지만 예외 발생 가능성이 있다.

		//예외 미루기 : 메소드 명 뒤에 throws Exception 붙이기
		String input = reader.readLine();
		
	}

예외 던지기, throw new Exception

  • 강제적으로 에러 발생 시킨다.
		try {
			if (num % 2 == 1) {
				throw new Exception("홀수 입력");	//강제적으로 에러 발생
			}
			
			System.out.println("업무 진행..");
			
		} catch (Exception e) {
			System.out.println("예외 처리..");
			System.out.println(e.getMessage());
		}
profile
웹백엔드개발자를 꿈꾸는

0개의 댓글