학습 목표
1.예외 처리(Exception Handling)의 개념과 사용 방법을 이해한다.
2.프로그램에서 발생하는 오류의 종류와 처리 방법을 학습한다.
3.상속을 활용하여 사용자 정의 예외 클래스를 만드는 방법을 익힌다.
1. 예외처리란?
-예외 처리 (Exception Handling)는 프로그램 실행 중 발생할 수 있는 예상치 못한(예외)을 관리하는 방법입니다.
이를 통해 프로그램의 비정상 종료를 방지하고 안정성과 신뢰성을 높일 수 있습니다.
1.1 예외 처리 구문
자바에서는 try, catch,finally,throws,throw 키워드를 사용하여 예외를 처리합니다.
try -catch문
try {
// 예외가 발생할 수 있는 코드
} catch (ExceptionType1 e) {
// ExceptionType1 예외를 처리하는 코드
} catch (ExceptionType2 e) {
// ExceptionType2 예외를 처리하는 코드
}
try-catch-finally문
try {
// 예외가 발생할 수 있는 코드
} catch (Exception e) {
// 예외 처리 코드
} finally {
// 항상 실행되는 코드
}
-finally 블록은 try 또는 catch 블록의 실행 여부와 관계없이 항상 실행됩니다. 자원 해제(예 : 파일 닫기)에
주로 사용됩니다.
thow와 throws
throw: 예외를 강제로 발생시킵니다,
if (someCondition) {
throw new Exception("Custom Error Message");
}
throws:메서드가 발생시킬 수 있는 예외를 선언합니다.
public void someMethod() throws IOException, NullPointerException {
// 예외가 발생할 수 있는 코드
}
2.프로그램에서의 오류와 처리 방법
2.1 오류의 종류
컴파일 오류(compile Error)
-코드 작성 중 발생하는 문법적 오류,
-예 : 세미콜론(;)누락, 잘못된 변수 선언,
- 현대 IDE(예: Ecilpse, intellij)는 컴파일 오류를 실시간으로 감지하여 수정이 용이함.
실행오류(Runtime error)
- JVM에서 발생하는 심각한 오류로, 프로그래머가 처리할 수 없는 문제.
-예 : fileNotFoundException(파일 없음);,SQLException(DB 연결 실패).
-자바는 안전성을 위해 대부분의 예외를 문법적으로 처리하도록 요구.
최상위 클래스 : Thowable
하위클래스:Error와 Exception
-Error 시스템 레벨의 심각한 오류.
-Exception:프로그램에서 처리가능한 예외
💡 팁: 시나Exception은 프로그램에서 처리 가능한 예외를 다루는 데 사용되며, Error는 일반적으로 처리하지 않습니다.
3.예외 처리 예제
시나리오 코드 1 - 예외처리해보기(try - catch)
package exception;
public class ArrayExceptionHandling {
public static void main(String[] args) {
// 배열 - 5
// 인덱스의 길이 - 4
int[] arr = {1, 2, 3, 4, 5};
// 예외 처리 try-catch 구문에 이해
// 예외 처리 try-catch-finally 구문에 이해
try {
// 예외가 발생할 가능성이 있는 코드를 넣어준다.
for (int i = 0; i < 10; i++) {
System.out.println("arr[" + i + "] = " + arr[i]);
}
} catch (ArrayIndexOutOfBoundsException e1) {
System.out.println("배열에 범위를 넘었어요!");
} catch (Exception e2) {
System.out.println(e2.getClass());
// 예외가 발생 했다면 예외 처리를 만들어 줄 수 있다.
// System.out.println("나의 예외 처리 : " + e.getMessage());
}
System.out.println("비정상 종료되지 않았습니다");
} // end of main
}-----------------------------------------------------------------------------------------
시나리오 코드 2 -예외 처리해보기(try - catch - finally)
package exception;
import java.util.InputMismatchException;
import java.util.Scanner;
public class FinallyHandling {
public static void main(String[] args) {
// try-catch-finally
Scanner scanner = new Scanner(System.in);
try {
System.out.print ("숫자를 입력해주세요:");
int result = scanner.nextInt();
System.out.println("입력한 숫자 : " + result);
// return;
} catch (InputMismatchException e1) {
System.out.println("잘못입력 했어요 숫자 입력해야 됨");
} catch (Exception e2) {
System.out.println(e2.getClass()); // e2.getClass()는 어떤 예외 타입이 발생했는지 알려줍니다.
System.out.println("입력 오류 !!!");
} finally {
// 반드시 수행 되어야 하는 코드를 입력하는 영역
// 심지어 return 키워드를 만나더라도 여기는 수행이 됩니다.
scanner.close(); // 스트림을 , 자원을 해제 합니다.
System.out.println("자원을 해제 했습니다.");
}
System.out.println("프로그램이 비정상 종료 안됨!");
}
}
--------------------------------------------------------------------------------------------------
시나리오 코드 3- throws(예외 처리 던지기, 미루기)
package exception;
public class ThrowsHandling {
public static void main(String[] args) {
Calc calc = new Calc();
// try {
// int result = calc.divide(10, 0);
// System.out.println("result : " + result);
// } catch (Exception e) {
// System.out.println(e.getClass());
// System.out.println("에러 발생");
// }
try {
calc.divide(10, 0);
} catch (Exception e) {
System.out.println("인수로 0을 넣지 마세요");
//throw new RuntimeException(e);
}
} // end of main
} // end of class
class Calc {
// 예외 발생할 수 있는 코드에서 직접 예외처리를 할 수 있지만
// 사용하는 시점(사용하는 사람이) 알아서 적절하게 예외처리를 던질 수 있다.
public int divide(int n1, int n2) throws ArithmeticException, Exception {
return n1 / n2;
}
}
---------------------------------------------------------------------------------------------------------
시나리오 코드 4 - throw(예외 클래스 직접 생성해서 발생 시키기)
package exception;
public class ThrowHandling {
public static void main(String[] args) {
boolean flag = true;
if(flag) {
// 필요에 의해서 직접 미리 만들어 둔 예외 클래를 생성할 수 있다.
// new ArithmeticException();
throw new ArithmeticException();
}
} // end of main
} // end of class
-----------------------------------------------------------------------------------------------
상속을 활용한 사용자 정의 예외 클래스 만들기
package exception;
public class ExceptionTest1 {
public static void main(String[] args) {
// 사용자 정의 예외 클래스 사용해 보기
int result = 0;
Calc2 calc2 = new Calc2();
try {
calc2.divide(10, 0);
} catch (DivideByZeroException e) {
throw new RuntimeException(e);
}
}
}
class Calc2 {
public int divide(int n1, int n2) throws DivideByZeroException {
int result = 0;
try {
result = n1 / n2;
} catch (Exception e) {
// 우리가 만든 사용자 정의 예외 클래스를 사용
throw new DivideByZeroException("0으로 나누지 마세요");
}
return result;
}
}
'JAVA 유용한 클래스' 카테고리의 다른 글
(JAVA)자바 multi-threading 이란 - 6 (0) | 2025.04.25 |
---|---|
(JAVA)자바 Thread - 5 (0) | 2025.04.25 |
(JAVA)String, StringBuffer (0) | 2025.04.24 |
(JAVA)자바 API 문서 확인해 보기 - 2 (0) | 2025.04.24 |
(JAVA)Object 클래스란 뭘까? - 1 (0) | 2025.04.24 |