본문 바로가기
JAVA

예외처리

by 영카이브 2024. 1. 31.

오류의 종류

  • 구문오류
  • 논리오류
  • 예외

 

예외란?

누군가만, 어떤 컴퓨터만, 어떤 상황에서만 예외적으로 발생하는 오류를 말한다.

예외는 데이터 입출력에서 발생한다.

 

 

예외처리는 무엇인가?

파일을 입출력할 때 하드디스크를 직접 이용하는 것이 아닌 인터페이스를 사용해 하드디스크를 엑세스한다. 이 인터페이스를 API라고 한다. API는 데이터를 입출력할 때 권한이 있는지, 파일이 존재하는지, 파일 용량이 충분한지 체크한다. API는 프로그램에 예외를 만났다는것을 보고한다.

 

 

예외처리 과정

 

1. 예외 보고

  • 예외를 발생시키는 것을 의미한다.
  • 예외클래스에 대한 객체화해서 throw한다. 
  • throw : 메서드에서 예외상황을 감지했을 때, 그것을 호출한 쪽에 알린다. 예외를 던지면 그 즉시 실행은 중지된다.
  • throws : 메서드 선언부에 사용되며, 해당 메서드가 예외를 던질 수 있다는 것을 나타낸다. 이는 메서드를 호출한 곳에서 예외처리를 해야함을 알려준다.
public class Calculator {
	public Calculator() {
	}
	public static int add(int x, int y) throws 천을_넘는_예외, 음수가_되는_예외 {
		int result = x + y; 
		if (result > 1000)
			throw new 천을_넘는_예외();
		if(result < 0)
			throw new 음수가_되는_예외();
		return x+y; 
	}
	public static int sub(int x, int y) {
		return x-y; 
	}
	public static int multi(int x, int y) {
		return x*y; 
	}
	public static int div(int x, int y) {
		return x/y; 
	}
}
}

 

 

예외를 처리하지않아 빨간줄이 그어졌다. >>> Add throws declaration 선택( 메인함수도 책임지지않겠다는 의미 ) 

 

 

예외가 던져지면 프로그램이 result = Calculator.add(3,-4); 에서 끝난다.

왜냐하면 main함수에서 던졌기 때문에 보고받는것은 자바 런타임환경이기 때문이다.

자바 런타임환경은 이것이 치명적인 예외인지, 논리적인예외인지 다음에 어떠한것을 수행해야할지 알지 못하므로 프로세스를 종료한다.

즉 예외를 처리하지 않고 런타임환경에 던진것이다.

public class Program {

	public static void main(String[] args) throws 천을_넘는_예외, 음수가_되는_예외 {
		Calculator calc = new Calculator();
		int result = 0 ; 
		result = Calculator.add(3,-4); 
		System.out.printf("add : %d\n" , result);
		result = Calculator.sub(3,4);
		System.out.printf("sub : %d\n" , result);
		result = Calculator.multi(3,4);
		System.out.printf("multi : %d\n" , result);
		result = Calculator.div(3,4);
		System.out.printf("div : %d\n" , result);
	}
}

 

 

 

 

2. 예외 처리

  • 예외에 대한 안내메시지를 사용자에게 안내한다.
  • 치명적인지 아닌지에 따라서 코드 계속 이어갈지에 대해 판단하게 해준다.
  • try-catch 블록을 사용하여 예외를 처리하고, 예외가 발생할 때 실행할 대체 코드 블록을 제공한다.

 

try-catch블록을 설정한것만으로 끝까지 실행되어 출력된다.

 

 

특정 예외에 대해 일관적인 메시지를 전달할 경우 

public class 천을_넘는_예외 extends Exception {
	@Override
	public String getMessage() {
		return "입력 값의 합이 1000을 넘는 오류가 발생하였습니다.";
	}
}
public class Program {

	public static void main(String[] args) throws 음수가_되는_예외 {
		Calculator calc = new Calculator();
		int result = 0 ; 
		try {
			// 보고됨
			result = Calculator.add(3,1004); 
		}
		catch(천을_넘는_예외 e) {
			// 보고가 된것을 잡아서 처리
			System.out.println(e.getMessage());
		}
		System.out.printf("add : %d\n" , result);
		result = Calculator.sub(3,4);
		System.out.printf("sub : %d\n" , result);
		result = Calculator.multi(3,4);
		System.out.printf("multi : %d\n" , result);
		result = Calculator.div(3,4);
		System.out.printf("div : %d\n" , result);
	}
}

 

 

3. 다중 예외 처리

 

Add catch clause to surrounding try : 여러개 예외를 개별 처리
Add exception to existing cathc clause : 여러개 예외를 하나로 처리

 

다중 catch를 이용해 예외 처리를 한 예시

if-else 부분 처럼 점점 범위가 넓어질수록 아래에 두고 해당 예외조건에 해당 될시 그에 따른 처리를 한다.

finally는 무조건 마지막에 실행된다.

 

 

 

4. UnChecked 예외 처리

 

Uncecked Exception

  • RuntimeException을 상속하는 클래스
  • 런타임 단계에서 확인 가능
  • 에러 처리를 강제하지 않는다.
public class 천을_넘는_예외 extends RuntimeException {
	@Override
	public String getMessage() {
		return "입력 값의 합이 1000을 넘는 오류가 발생하였습니다.";
	}
}
public class Program {

	public static void main(String[] args){
		Calculator calc = new Calculator();
		int result = 0 ; 
		result = Calculator.add(3,1004); 
		System.out.printf("add : %d\n" , result);
		result = Calculator.sub(3,4);
		System.out.printf("sub : %d\n" , result);
		result = Calculator.multi(3,4);
		System.out.printf("multi : %d\n" , result);
		result = Calculator.div(3,4);
		System.out.printf("div : %d\n" , result);
	}
}

 

Exception in thread "main" 천을_넘는_예외: 입력 값의 합이 1000을 넘는 오류가 발생하였습니다.

at Calculator.add(Calculator.java:8)

at Program.main(Program.java:7)

 

 

 

 

참고 자료 출처 : https://www.youtube.com/watch?v=zRCHgtxl2vs

https://www.youtube.com/watch?v=mj54qui7810

'JAVA' 카테고리의 다른 글

인스턴스 메서드와 정적 메서드  (0) 2024.02.04
인터페이스  (0) 2024.01.28
다형성과 형변환  (0) 2024.01.27
탬플릿 메서드 패턴 & 팩토리 메서드패턴  (0) 2024.01.24
메서드 동적 바인딩  (0) 2024.01.19