뚜sh뚜sh

예외 처리 본문

Language/Java

예외 처리

뚜sh뚜sh 2023. 7. 3. 21:02

개념

- 예외 처리는 프로그램 실행 도중에 발생되는 오류를 처리하기 위한 부분이다

- 에러 : 수정할 수 없는 것

- 오류 : 수정 가능, 알려주는 역할

- 키워드 : try, catch, finally, throws

 

 

 

형식

- 기본 형식

try {
	// 예외가 발생할 수 있는 문장
} catch (Exception형 e) {
	// 예외가 발생했을 때 처리하는 문장

- Exception 형 -> java.lang

package test1;

public class test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int nVar = 0;
		int nResult;
		
		try {
			nResult = 7 / nVar;
		} catch (ArithmeticException e) {
			System.out.println("failed");		}
	}
}

- 자주 사용되는 Exception 형 클래스

- 여러 예외처리 형식

try {
	// 예외가 발생할 수 있는 문장
} catch (Exception형 e) {
	// 예외가 발생했을 때 처리하는 문장
} catch (Exception형 e) {
	// 예외가 발생했을 때 처리하는 문장
}
package test1;

public class test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int nVar[] = {0, 1, 2, 3, 4};
		
		try {
			for (int i = 0; i < 6; i++)
				System.out.println(nVar[i]);
		} catch (ArithmeticException e) {
			System.out.println("ArithmeticException");
		} 
		catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("Array Index Error");
		}

	}
}

 

 

 

finally

- try ~ catch문의 예외처리와 상관없이 항상 실행해야 하는 문장이 있는 경우에 사용

try {
	
} catch (Exception형 e) {
	
} finally {
	// 예외처리와 상관없이 항상 실행해야 하는 문장
}

 

 

 

finally 사용 예

1. 예외가 발생하지 않는 프로그램의 실행에서 finally의 예

package test1;

public class test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int nVar = 7;
		int nResult;
		
		try {
			nResult = 7 / nVar;
		} catch (ArithmeticException e) {
			System.out.println("ArithmeticException");
		} finally {
			System.out.println("GOOD");
		}

	}
}

 

2. 예외가 발생했을 때 실행되는 finally의 예

package test1;

public class test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int nVar = 0; // <- 예외발생 값
		int nResult;
		
		try {
			nResult = 7 / nVar;
		} catch (ArithmeticException e) {
			System.out.println("ArithmeticException");
		} finally {
			System.out.println("GOOD");
		}

	}
}

 

 

 

throws

- 모든 예외 처리를 try ~ catch 안의 괄호에 넣어 처리하기에는 무리가 있다 => JVM 또는 예외 처리 클래스를 지정

반환형 메소드() throws Exception {
	
}
package test1;

public class test1 {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		int nVar = 0; // <- 예외발생 값
		int nResult;
		
		nResult = 7 / nVar;
		System.out.println(nResult);
	}
}

'Language > Java' 카테고리의 다른 글

유용한 클래스들  (0) 2023.07.05
내부 클래스와 익명 클래스  (0) 2023.07.03
인터페이스(interface)  (0) 2023.07.03
추상 클래스(abstract class)  (0) 2023.07.03
상속(Inheritance)  (0) 2023.07.03
Comments