예외 처리

Java

목록 보기
13/26
post-thumbnail

1. 실행예외(RuntimeException)

1-1. NullpointException

객체 참조가 없는 상태, 즉 null값을 갖는 참조변수로 객체 접근 연산자인 도트(.)를 사용했을 때 발생

String data = null;
System.out.println(data.toString());

1-2. ArrayIndexOutOfBoundsException

배열에서 인덱스 범위를 초과하여 사용할 경우 발생

1-3. NumberFormatException

문자열을 숫자로 변환하는 경우가 많다. 이 중 숫자로 변환될 수 없는 문자가 포함되어 있을 경우 발생.
ex) "a100"을 숫자로 변환하려고 할 경우

1-4. ClassCastException

(타입 변환이 되지 않을 경우 발생)

2. 예외 처리 코드(try-catch-finally)

public class tryCatchExeption {

	public static void main(String[] args) {
		try {
			Class clazz = Class.forName("java.lang.String2");
		}catch (ClassNotFoundException e) {
			System.out.println("클래스가 존재하지 않습니다.");
		} finally {
			System.out.println("프로그램을 종료합니다");
		}
	}
}

2-1. 다중 catch

  • catch 순서

    첫 번째 경우에는 컴파일 오류가 발생함 : unreachable 오류

2-2. 멀티 catch

2-3. 자동 리소스 닫기(try-with-resources)

try ( ... ) { ... }
예외 발생 여부와 상관없이 사용했던 리소스 객체(각종 입출력 스트림, 서버소켓, 소켓, 각종 채널)의 close() 메소드를 호출해서 안전하게 리소스를 닫아준다.
이해하기 어려우면 노

2-4. 예외 떠넘기기(throws)

public void method1() {
   try {
       method2();
    } catch(ClassNotFountException e) {
   //예외 처리 코드
    System.out.println("클래스가 존재하지 않습니다.");
      }
  }
 public coid nethod2() throws ClassVotFoundWxception {
     Class clazz = Class.foorName("java.lang.String2");
          }

2-5. 사용자 정의 예외 클래스 선언

  • 사용자 정의 예외 클래스 선언
public class XXXException extends [Exception | RuntimeException] {
	public XXXException() {  }
	public XXXException(String message) {super(message);}
}

일반 exception이면 앞에거, 런타임 exception이면 뒤에꺼.

  • 예외 발생 시키기
throw new XXXException()
throw new XXXException("메시지");
public void methid() throws XXXException {
	throw new XXXException("메시지");
}

throw와 thros는 완전히 다른 역할!

2-6. 예외 정보 얻기

  • getMessage() : 예외를 발생시킬 때 생성자 매개값으로 사용한 메시지를 리턴
  • catch() 절에서 활용
} catch(Exception e) {
	String message = e.getMessage();
}
  • printStackTrace() : 예외 발생 코드를 추적한 내용을 모두 콘솔에 출력한다

0개의 댓글