-
ChatGPT로 Java 공부하기 #2 자바의 예외 처리와 실전 예제ChatGPT로 공부하기/Java 2024. 11. 19. 17:24

자바의 예외 처리와 실전 예제
1. 자바의 예외 처리란?
예외(Exception)란?
- 정의: 프로그램 실행 중에 발생하는 비정상적인 상황
- 종류:
- Checked Exception: 컴파일 시점에 반드시 처리해야 하는 예외 (예: IOException, SQLException)
- Unchecked Exception: 런타임 시 발생하는 예외 (예: NullPointerException, ArrayIndexOutOfBoundsException)
자바의 예외 처리 방법
자바는 예외 처리를 위해 try-catch-finally 블록을 제공합니다.
2. 예외 처리 기본 문법
2.1 try-catch 블록
예외가 발생할 수 있는 코드를 try 블록에 작성하고, 발생한 예외를 catch 블록에서 처리합니다.
public class ExceptionExample { public static void main(String[] args) { try { int result = 10 / 0; // ArithmeticException 발생 } catch (ArithmeticException e) { System.out.println("예외 발생: " + e.getMessage()); } } }2.2 finally 블록
finally 블록은 예외 발생 여부와 상관없이 항상 실행됩니다.
public class FinallyExample { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException 발생 } catch (ArrayIndexOutOfBoundsException e) { System.out.println("예외 발생: " + e.getMessage()); } finally { System.out.println("이 블록은 항상 실행됩니다."); } } }2.3 throw와 throws
- throw: 예외를 직접 발생시킬 때 사용
- throws: 메서드가 예외를 던질 가능성을 명시
public class ThrowThrowsExample { public static void main(String[] args) { try { validateAge(15); } catch (IllegalArgumentException e) { System.out.println("예외 처리: " + e.getMessage()); } } public static void validateAge(int age) throws IllegalArgumentException { if (age < 18) { throw new IllegalArgumentException("나이는 18 이상이어야 합니다."); } } }
3. 실무 적용 예제
요구사항
- 사용자 입력에서 숫자가 아닌 값을 입력하면 프로그램이 종료되지 않고 적절한 메시지를 출력해야 함.
- 데이터베이스 연결 시, 실패할 경우 사용자에게 연결 실패 메시지를 출력.
3.1 사용자 입력 예외 처리
import java.util.Scanner; public class InputValidation { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number = 0; while (true) { System.out.print("숫자를 입력하세요: "); try { number = Integer.parseInt(scanner.nextLine()); // 숫자 변환 시도 break; // 성공하면 반복문 종료 } catch (NumberFormatException e) { System.out.println("유효하지 않은 입력입니다. 숫자를 입력해주세요."); } } System.out.println("입력된 숫자: " + number); scanner.close(); } }
3.2 데이터베이스 연결 예외 처리
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DatabaseConnection { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mydb"; String user = "root"; String password = "password"; Connection connection = null; try { // 데이터베이스 연결 시도 connection = DriverManager.getConnection(url, user, password); System.out.println("데이터베이스 연결 성공!"); } catch (SQLException e) { System.out.println("데이터베이스 연결 실패: " + e.getMessage()); } finally { // 연결 종료 if (connection != null) { try { connection.close(); System.out.println("연결이 종료되었습니다."); } catch (SQLException e) { System.out.println("연결 종료 중 예외 발생: " + e.getMessage()); } } } } }
4. 사용자 정의 예외
실무에서는 특정 비즈니스 로직에 대한 예외를 사용자 정의 예외로 처리할 수 있습니다.
예제: 주문 금액이 0 이하일 때 예외 발생
class InvalidOrderAmountException extends Exception { public InvalidOrderAmountException(String message) { super(message); } } public class CustomExceptionExample { public static void main(String[] args) { try { processOrder(-500); } catch (InvalidOrderAmountException e) { System.out.println("예외 처리: " + e.getMessage()); } } public static void processOrder(int amount) throws InvalidOrderAmountException { if (amount <= 0) { throw new InvalidOrderAmountException("주문 금액은 0보다 커야 합니다."); } System.out.println("주문 처리 완료: " + amount + "원"); } }'ChatGPT로 공부하기 > Java' 카테고리의 다른 글
ChatGPT로 Java 공부하기 #3 자바 컬렉션 프레임워크와 주요 클래스 (0) 2024.11.19 ChatGPT로 Java 공부하기 #1 자바의 기본 문법 및 객체 지향 개념 정리 (3) 2024.11.19