[ Exception and Error ] 예외 와 에러 차이점 - kuyeol/Document GitHub Wiki
Type / How to Recognize / Okay for program to catch? / Is program required to handle or declare? RuntimeException / Subclass od RuntimeException / yes / no Checked exception / Subclass of Exception but not subclass of RuntimeException / yes / yes Error / Subclass of Error / No /No
예외 (Exception )
[!note]
- 메서드 호출 시 구현 의도와 다른 결과를 발생할 수 있는 경우
- 의도적으로 발생 시키고(throw), 잡아서(catch) 처리
- 예: 사용자 입력 오류, 파일 못 찾음, 네트워크 연결 실패 등
체크 예외는 반드시 처리하거나 던져야 하고, 런타임 예외는 필요에 따라 처리함
에러 (Error)
→ 시스템이나 JVM 레벨에서 발생하는 심각한 문제 (보통 버그 아님) → 예: 메모리 부족, 스택 오버플로우
버그(Bug)
→ 코드 작성 실수나 설계 오류 때문에 생기는 문제 → 예: 조건문 잘못 썼다, 변수 초기화 안 했다, 배열 범위 넘었다 등 → 결과적으로 프로그램이 이상하게 동작하거나 예외가 발생함
Types of exceptions and errors
타입 | 인식 방법 | 프로그램이 잡아도 되는가? | 프로그램이 반드시 처리하거나 선언해야 하나? |
---|---|---|---|
런타임 예외 | RuntimeException 의 하위 클래스 |
예 | 아니요 |
체크 예외 | Exception 의 하위 클래스이지만 RuntimeException 은 아님 |
예 | 예 |
에러 (Error) | Error 의 하위 클래스 |
아니요 | 아니요 |
출처: OCP_Oracle_Certification_professional_JavaSe_11
기본적인 예외 발생 상황을 다른 메서드로 예외 안나오도록 캐치
예외 처리 흐름 예시
기본적인 예외 발생 상황을 다른 메서드로 예외 안나오도록 캐치
- 예외가 발생할 수 있는 메서드:
indexOf
- Index 0 out of bounds for length 0 예외 발생
public static int indexOf( String[] args )
{
for ( int i = 0 ; i < args.length ; i++ ) {
if ( !args[i].isEmpty() ) {
return i;
}
}
return -1;
}
배열을 메서드 호출해 확인후 값이 존재할경우 실행 아니면 안내메세지 출력
public static void main( String[] args ) {
// args= new String[]{"A","B"};
int validateArgs = indexOf( args );
if ( validateArgs > -1 ) {
for ( int i = 0 ; i < args.length ; i++ ) {
System.out.println( args[i] );
}
}else {
System.out.println("Args is Null");
}
}
의도 된 출력이 아닌 경우를 정의 하여 조건과 동일 하지 않은 경우 예외를 출력
public static void vaildException( String args )
{
try{
if ( args.length() < 2 ){
throw new RuntimeException( "length is short" );
}
}catch (RuntimeException e ){
e.printStackTrace();
}
}
배열 객체의 길이가 조건과 다른경우 출력
public static void main( String[] args )
{
//args= new String[]{"A","B"};
int validateArgs = indexOf( args );
if ( validateArgs > -1 ) {
for ( int i = 0 ; i < args.length ; i++ ) {
vaildException(args[i]);
System.out.println( args[i] );
}
}else {
System.out.println("Args is Null");
}
}