스파르타 8일차

임선구·2026년 3월 18일

스파르타

목록 보기
8/14

챕터3-1 : 예외(Exception)과 예외처리(try-catch)

예외(Exception)란?

의도하지 않은 예외

public class Main {
    public static void main(String[] args) {
        System.out.println("프로그램 시작");
        int result = 10 / 0; // ❌ 예외 발생 (ArithmeticException)
        System.out.println("이 문장은 실행되지 않음");
    }
}```

```java
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at chapter3.exception.Main.main(Main.java:8)

Process finished with exit code 1

의도적인 예외 - throw

public class Main {
    public static void main(String[] args) {
        int age = 10;
        if (age < 18) {
		        // ✅ 의도적으로 예외를 발생시키는 부분
            throw new IllegalArgumentException("미성년자는 접근할 수 없습니다!");
        }
        System.out.println("....");
    }
}

예외 구조와 종류


예외 전파

RuntimeException - UncheckedException

try-catch 활용

public class ExceptionPractice {
    public void callUncheckedException() {
        if (true) {
            System.out.println("언체크 예외 발생");
            throw new RuntimeException(); // ✅ 예외발생 
        }
    }
}
public class Main {
    public static void main(String[] args) {
        // 예외 실습 객체 인스턴스화
        ExceptionPractice exceptionPractice = new ExceptionPractice();

        // ✅ 언체크 예외 호출
        exceptionPractice.callUncheckedException();
        
        // ❌ 예외처리를 해주지 않았기 때문에 프로그램이 종료됩니다.
        System.out.println("이 줄은 실행되지 않습니다."); 
    }
}
public class Main {

    public static void main(String[] args) {
        ExceptionPractice exceptionPractice = new ExceptionPractice();
        
        // ✅ 상위로 전파된 예외처리
        try {
            exceptionPractice.callUncheckedException();

        } catch (RuntimeException e) { // ✅ 예외처리
            System.out.println("언체크 예외 처리");   
            
        } catch (Exception e) {
            System.out.println("체크 예외 처리");
        }

        System.out.println("프로그램 종료");
    }
}

Exception - CheckedException

try-catch 활용

public class ExceptionPractice {

    public void callCheckedException() {
		    // ✅ try-catch 로 예외 처리
        try { 
            if (true) {
                System.out.println("체크예외 발생");
                throw new Exception();
            }
        } catch (Exception e) {
            System.out.println("예외 처리");
        }
    }
}
public class Main {
    public static void main(String[] args) {
        
        // 예외 실습 객체 인스턴스화
        ExceptionPractice exceptionPractice = new ExceptionPractice();

        // ✅ 체크예외 호출
        exceptionPractice.callCheckedException();
    }
}

throws 활용

public class ExceptionPractice {

    public void callCheckedException() throws Exception { // ✅ throws 예외를 상위로 전파
        if (true) {
            System.out.println("체크예외 발생");
            throw new Exception();
        }
    }
}
package chapter3.exception;

public class Main {
    public static void main(String[] args) {

        // 예외 실습 객체 인스턴스화
        ExceptionPractice exceptionPractice = new ExceptionPractice();

        // 체크 예외 사용
        // ✅ 반드시 상위 메서드에서 try-catch 를 활용해 주어야합니다.
        try {
            exceptionPractice.callCheckedException();
        } catch (Exception e) {
            System.out.println("예외처리");
        }
    }
}

챕터3-2 : Optional - null 을 다루는 법

Optional 이란?

Optional 이 왜 필요한가?

public class Student {

    // 속성
    private String name;
    
    // 생성자
    
    // 기능
    public String getName() {
        return this.name;
    }
}
public class Camp {

    // 속성
    private Student student;

    // 생성자
    
    // 기능: ⚠️ null 을 반환할 수 있는 메서드
    public Student getStudent() {
        return student;
    }
    
    public void setStudent(Student student) {
		    this.student = student;    
    }
}
public class Main {

    public static void main(String[] args) {

        Camp camp = new Camp();
        Student student = camp.getStudent(); // ⚠️ student 에는 null 이 담김
        // ⚠️ 아래 코드에서 NPE 발생! 컴파일러가 잡아주지 않음
        String studentName = student.getName(); // 🔥 NPE 발생 -> 프로그램 종료
        System.out.println("studentName = " + studentName);
    }
}

NULL 을 직접 처리의 한계

public class Main {
    public static void main(String[] args) {
        Camp camp = new Camp();
        Student student = camp.getStudent();

        String studentName;
        if (student != null) { // ⚠️ 가능은하지만 현실적으로 어려움
            studentName = student.getName();
        } else {
            studentName = "등록된 학생 없음"; // 기본값 제공
        }

        System.out.println("studentName = " + studentName);
    }
}

Optional 활용하기


import java.util.Optional;

public class Camp {

    // 속성
    private Student student;

    // 생성자

    // 기능
    // ✅ null 이 반환될 수 있음을 명확하게 표시
    public Optional<Student> getStudent() {
        return Optional.ofNullable(student);
    }
    
    public void setStudent(Student student) {
		    this.student = student;    
    }
}
public class Main {

    public static void main(String[] args) {

        Camp camp = new Camp();
        
        // isPresent() 활용시 true 를 반환하고 싶을때 활용
        // Student newStudent = new Student();
        // camp.setStudent(newStudent);

        //  Optional 객체 반환받음
        Optional<Student> studentOptional = camp.getStudent();

        // Optional 객체의 기능 활용
        boolean flag = studentOptional.isPresent(); // false 반환
        if (flag) {
            // 존재할 경우
            Student student = studentOptional.get(); // ✅ 안전하게 Student 객체 가져오기
            String studentName = student.getName();
            System.out.println("studentName = " + studentName);

        } else {
            // null 일 경우
            System.out.println("학생이 없습니다.");
        }
    }
}

import java.util.Optional;

public class Camp {

    // 속성
    private Student student;

    // 생성자

    // 기능
    // ✅ null 이 반환될 수 있음을 명확하게 표시
    public Optional<Student> getStudent() {
        return Optional.ofNullable(student);
    }
}

import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        Camp camp = new Camp();

        // ✅ Optional 객체의 기능 활용 (orElseGet 사용)
        Student student = camp.getStudent()
                              .orElseGet(() -> new Student("미등록 학생"));

        System.out.println("studentName = " + student.getName());
    }
}
profile
끝까지 가면 내가 다 이겨

0개의 댓글