본문 바로가기

자바(JAVA)
[자바(Java)] 에러(Error)

//에러, Error

- 오류, 버그(Bug), 예외(Exception) 등..

1. 컴파일 에러
- 컴파일 작업 중에 발생하는 에러
- 컴파일러가 번역하다가 발견
- 미리 약속한 문법에서 조금이라도 틀리면 번역하지 못 함.
- 컴파일 에러 발생 시 전체 컴파일 작업 중단 > 프로그램 실행 파일 생성 불가
- 반드시 해결해야 하는 오류
- 난이도 가장 낮음 > 발견이 쉬움(컴파일러가 알려준다) > 고치기 쉬움
- 이클립스의 빨간 줄 > 컴파일 에러 > 이클립스가 실시간 컴파일러와 연동되어, 
  컴파일 작업 전이라도 컴파일 불가능 문법 오류를 발견하면 바로 빨간 밑줄로 표시해 준다. 
- 해결 방법: 에러 메시지 확인 > 코드 수정

2. 런타임 에러
- 런타임(Runtime) : 실행 중
- 컴파일 작업 중에는 발견하지 못했는데 실행 중에 발생하는 에러
- 문법에는 오류가 없는데 다른 원인으로 발생하는 에러
예외(Exception) > 특정 상황에서 발생함.
- 난이도 중간 > 발견이 복불복.. > 충분한 테스트 필요 > 인력 + 돈 + 시간 > 출시 
    > 잠재적으로 런타임 오류 내재 > 업그레이드, 패치 수정.. 

3. 논리 에러
- 컴파일 성공 + 실행 성공 but 일부 결과 이상..
- 난이도 최상 > 발견 최악..


// 예외 처리, Exception

- 예외 처리에서 가장 중요한 것
    1. Friendly message to end user (시스템의 최종 사용자에게 예외에 대한 메시지를 친절하게 전달하기)
    2. Enough information to Debug the problem (어떤 작업이나 단계를 거쳐야 하는지 알려주기)

- 오류 직접 처리
     ~ try-catch
     ~ try-catch-finally
     ~ try-with-resources

- 오류 간접 처리
     ~ throws

- 의도적으로 예외  발생
    ~ throw


// 오류의 순위, Exception Hierarchy

- Throwable : 예외 처리 관련 슈퍼 클래스(가장 상위 클래스)
      ~ Error: 프로그래머가 처리할 수 없는 오류 ex) stack overflow

      ~ Exception: 프로그래머가 충분히 해결할 수 있는 오류
          ~~ Checked Exceptions: Exception이라는 항목 아래 RuntimeException(RuntimeException의 자식 포함)이 아닌 것들

          ~~ RuntimeException: Unchecked Exeption     

 

  Checked Exceptions vs RuntimeException

- Checked Exceptions: 소비자가 예외를 처리해 주기를 바랄 때(예외가 생겼다는 것에 대해 알기를 바랄 때)

- RuntimeException: 소비자가 예외 상황에서 할 수 있는 것이 없을 때


// try-catch

- try 안에 실행할 코드를 넣고, catch 안에는 예외 발생시 실행할 코드를 넣는다.

package com.sorrel012.exceptionhandling;

public class ExceptionHandlingRunner2 {
	
	public static void main(String[] args) {

		method1();
		System.out.println("Main Ended");

	} //main

	private static void method1() {
		method2();
		System.out.println("Method1 Ended");
	}

	private static void method2() {
		try {
//			String str = null;
	//			str.length();
				int[] i = {1,2};
				int number = i[3];
			
			System.out.println("Method2 Ended");
		} catch (NullPointerException ex) {
			System.out.println("NullPointerException");
			ex.printStackTrace();
		} catch (ArrayIndexOutOfBoundsException ex) {
			System.out.println("ArrayIndexOutOfBounds Exception");
			ex.printStackTrace();
		} catch (Exception ex) {
			System.out.println("Matched Excpetion");
			ex.printStackTrace();
		}
	}
	
}

// try - catch - finally

- 예외가 발생하든 하지 않든, 반드시 실행해야 하는 코드가 있을 경우 finally를 사용한다.

※ System.exit(1) 을 사용할 경우 finally는 실행되지 않는다.
      > 웬만하면 절대 실행하지 않길.. 전체 응용 프로그램들과 충돌

package com.sorrel012.exceptionhandling;

import java.util.Scanner;

public class FinallyRunner {

	public static void main(String[] args) {
		
		Scanner scan = null;

		try {
			scan = new Scanner(System.in);
			
			int[] numbers = {12,3,4,5};

			int number = numbers[5];

			System.out.println("Before Scanner Close");
			
		} catch (Exception e ) {
			e.printStackTrace();
			
		} finally {
			System.out.println("Before Scanner Close");
			if(scan != null) {
				scan.close();
			}
		}
		
		System.out.println("Just before closing out main");

	} //main
	
}

// try-with-resources

- try() 안에 구문을 넣어준다.

- Autocloseable의 인터페이스를 구현하는 클래스나 인터페이스는  try-with-resources로 사용 가능하다.

- try() 안에서 스캐너를 생성했을 경우, 스캐너가 구현하고 있는 Autocloseable이 close() 메서드를 가지고 있기 때문에 코드에서 오류가 생겼을 경우, 자동으로 close 된다.


// throws

- 예외를 직접 처리하는 것이 아니라 현재 처리하기 어려워 예외 사항을 떠넘긴다.

- Checked Exception을 throw하는 경우 throws로 처리가 필요하다.

package com.sorrel012.exceptionhandling;

public class CheckedExceptionRunner {
	
	public static void main(String[] args) {
		try {
			someOtherMethod();
			Thread.sleep(2000);
			
		} catch(InterruptedException e){
			e.printStackTrace();
		}

	} //main
	
	private static void someOtherMethod() throws InterruptedException {
		Thread.sleep(2000);
	}

}

// throw

- 의도적으로 예외를 발생시킨다.

- Checked Exception을 발생시키는 경우, throws로 예외 처리를 해주어야 한다.

package com.sorrel012.exceptionhandling;

class Amount {
	
	private String currency;
	private int amount;
	
	public Amount(String currency, int amount) {
		super();
		this.currency = currency;
		this.amount = amount;
	}
	
	public void add(Amount that) {
		
		if(!this.currency.equals(that.currency)) {
			throw new RuntimeException("Currencies Don't Match");
		}
		
		this.amount = this.amount = that.amount;
	}
	
	@Override
	public String toString() {
		return amount + " " + currency;
	}
	
}

public class ThrowingExceptionRunner {
	
	public static void main(String[] args) {

		Amount amount1 = new Amount("USD", 10);
		Amount amount2 = new Amount("EUR", 20);
		amount1.add(amount2);
		
		System.out.println(amount1);

	} //main

}

package com.sorrel012.exceptionhandling;

class Amount {
	
	private String currency;
	private int amount;
	
	public Amount(String currency, int amount) {
		super();
		this.currency = currency;
		this.amount = amount;
	}
	
	public void add(Amount that) throws Exception {
		
		if(!this.currency.equals(that.currency)) {
			throw new Exception("Currencies Don't Match " + this.currency + " & " + that.currency);
		}
		
		this.amount = this.amount = that.amount;
	}
	
	@Override
	public String toString() {
		return amount + " " + currency;
	}
	
}

public class ThrowingExceptionRunner {
	
	public static void main(String[] args) throws Exception {

		Amount amount1 = new Amount("USD", 10);
		Amount amount2 = new Amount("EUR", 20);
		amount1.add(amount2);
		
		System.out.println(amount1);

	} //main

}

- RuntimeException 정의

package com.sorrel012.exceptionhandling;

class Amount {
	
	private String currency;
	private int amount;
	
	public Amount(String currency, int amount) {
		super();
		this.currency = currency;
		this.amount = amount;
	}
	
	public void add(Amount that) {
		
		if(!this.currency.equals(that.currency)) {
//			throw new Exception("Currencies Don't Match " + this.currency + " & " + that.currency);
			throw new CurrenciesDoNotMatchException("Currencies Don't Match " + this.currency + " & " + that.currency);
		}
		
		this.amount = this.amount + that.amount;
	}
	
	@Override
	public String toString() {
		return amount + " " + currency;
	}
	
}

class CurrenciesDoNotMatchException extends RuntimeException {
	
	public CurrenciesDoNotMatchException(String msg) {
		super(msg);
	}
}

public class ThrowingExceptionRunner {
	 	
	public static void main(String[] args){

		Amount amount1 = new Amount("USD", 10);
		Amount amount2 = new Amount("EUR", 20);
		amount1.add(amount2);
		
		System.out.println(amount1);

	} //main

}

//예외 메서드

e.toString() : 에러명을 문자열로 반환한다.

e.printStackTrace() : 자세한 에러 내용을 출력한다.(void)


	public boolean add(int index, String value) {
		
		try {

			if(index < 0 || index > this.index) {
				throw new IndexOutOfBoundsException();
			}
			
			for(int i = index; i < this.index - 1; i++) {
				list[i+1] = list[i];
			}
			
			list[index] = value;
			
			this.index++;
			
			return true;
			
		} catch(IndexOutOfBoundsException e) {
			System.out.println(e.toString() + ": " + errorMsg);
			return false;
		}
		
	}

'자바(JAVA)' 카테고리의 다른 글

[자바(Java)] 연산자  (0) 2023.02.06
[자바(Java)] DateTime  (0) 2023.02.06
[자바(Java)] 파일과 디렉토리  (0) 2023.01.24
☆이클립스 개인 설정  (0) 2023.01.14
[자바(Java)] BigInteger , BigDecimal  (0) 2023.01.06