Java Exception(예외)

JMS·2022년 1월 29일
0

Java

목록 보기
2/4
post-thumbnail
  • 에러 : 프로그램 코드에 의해 수습될 수 없는 심각한 오류
  • 예외 : 프로그램 코드에 의해서 수습될 수 있는 다소 미약한 오류

1. try-catch

  • 예외처리를 통해서 프로그램이 비정상적으로 종료되는 것을 방지할 수 있다.
  • 모든 예외는 Exception클래스의 자식 클래스이다.
  • RuntimeException클래스와 그 자식들은 예외처리가 강제되지 않는다.
  • [RuntimeException클래스와 그 자식들을 제외한]Exception클래스의 자식들은 예외처리가 강제된다.
  • try{ } catch(Exception e) { } : try블럭 안의 내용을 실행 중 예외가 발생하면 catch로 넘어간다.
  • catch의 파라미터로는 처리할 예외를 지정해준다.
  • 파라미터로 지정한 예외와 일치한 예외가 발생되면 catch블럭 안의 내용이 수행된 후 try-catch를 빠져나간다.
  • 지정한 예외와 일치하는 catch가 없을 경우 예외는 처리되지 않는다.
try {			
	int result = 10 / 0; // ArithmeticException 예외 발생
    	System.out.println(result);
}catch(ArithmeticException | IndexOutOfBoundsException e) {
// catch의 파라미터로 ArithmeticException를 지정했기 때문에 이 블럭에서 예외 처리
	e.printStackTrace();
}catch(NullPointerException e) {
// NullPointerException 예외는 발생되지 않았으므로 넘어감
}catch(Exception e) {
//모든 예외클래스의 부모클래스인 Exception 클래스로 모든 예외를 한번에 처리
}
  • 보통 catch의 파라미터로 자식클래스의 예외를 넣지않고 Exception클래스를 지정해 사용

2. throwException

throw new Exception( );

  • 예외를 발생시키는 명령어
  • 예외가 어떻게 발생되는지 상황을 테스트할때 사용
try {
	throw new IOException(); // catch로 예외를 처리하지 않고 예외를 발생시킨다.
} catch(Exception e) {
	e.printStackTrace();
}

3. throwsException

void method( ) throws Exception{ }

  • 메서드 호출시 발생할 수 있는 예외를 선언
  • 예외를 선언하면 예외처리를 하지 않고 자신을 호출한 메서드로 예외처리를 넘겨준다.
try {
//예외를 선언한 메서드는 호출할때 예외처리
	method();
} catch (IOException e) {
	e.printStackTrace();
}


private static void method() throws IOException { 
// method()를 실행하면 IOException예외가 발생될 수 있다고 선언하고 예외처리는 메서드 안에서 하지 않는다.
	}

4. 자주 발생하는 예외

1. NullPointerException : null을 참조했을때 발생

//NullPointerException
		String str = null;
		System.out.println(str.equals("abc"));

//출력 : Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "str" is null

2. ArrayIndexOutOfBoundsException : 배열 인덱스의 범위를 벗어났을때 발생

//ArrayIndexOutOfBoundsException
int[] arr = new int[10];
		
for(int i = 0; i <= arr.length; i++) {
//arr의 index는 9까지 있지만 i <= arr.length이므로 i = 10일때도 반복문이 실행되어 범위를 벗어난 arr[10]이 실행되므로 예외발생 
	System.out.println(arr[i]);
    }
//출력 : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
profile
비 전공 ZEROBASE 개발 꿈나무

0개의 댓글

관련 채용 정보