try와 catch

Java의 데이터 타입과 예외

Jim White

Java Developer

Java의 문제 상황

  • 애플리케이션에는 문제가 발생할 수 있음
    • 잘못된 입력
    • 코딩 오류
    • 예상치 못한 상황
  • 이러한 문제를 예외(exception)라고 함
    • 정상 제어 흐름을 방해함
  • Java는 예외를 던짐(throw)
Java의 데이터 타입과 예외

예외 예시

public static void main(String[] args) {
    ArrayList<String> allStars = new ArrayList<String>();
    allStars.add("Mays");
    allStars.add("Aaron");
    allStars.add("Ruth");
    String last = allStars.get(3); // This will cause an exception
    System.out.println(last);
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of 
bounds for length 3
Java의 데이터 타입과 예외

try

  • 예외를 발생시킬 수 있는 코드를 try 블록으로 감쌉니다
    • "이 코드를 시도하고 문제가 있으면 catch로 넘긴다"
try {
    // Statements to be executed and watched for exceptions
}
Java의 데이터 타입과 예외

catch

  • try 다음에 catch 블록을 둡니다
    • 예외 문제를 처리하는 핸들러 역할
    • 포착된 예외가 매개변수로 전달됨
  • try/catch는 일부 예외에 필수
    • 다른 예외에는 선택
try {
    // Statements to be executed and watched for exceptions
} catch (<Exception type> <variable name>) {
    // Statements to execute if an exception has occurred
}
Java의 데이터 타입과 예외

IndexOutOfBoundsException 처리

try {
  ArrayList<String> allStars = new ArrayList<String>();
  allStars.add("Mays");
  allStars.add("Aaron");
  allStars.add("Ruth");
  String last = allStars.get(3); // Accessing an element that isn't there
  System.out.println(last);
} catch (IndexOutOfBoundsException e) {
  System.out.println("Oops - wrong index");
}
Oops - wrong index
Java의 데이터 타입과 예외

여러 개의 catch

  • 여러 catch 블록으로 예외 유형별 처리
  • catch는 고유한 예외 타입과 변수 사용
  • 예외 발생 시, Java는 순서대로 catch를 확인해 일치 항목을 찾음
try {
    ArrayList<String> nums 
      = new ArrayList<String>();
    nums.add("one");
    String last = nums.get(0);
    Integer.valueOf(last);
    System.out.println(last);
} catch (IndexOutOfBoundsException eIndex) {
    System.out.println("Oops - wrong index");
} catch (NumberFormatException eValueOf) {
    System.out.println(
      "Oops - String not a number");
}
Oops - String not a number
Java의 데이터 타입과 예외

포괄적 catch

  • catch (Exception 변수){ }로 전체 예외를 포괄 처리
    • 다른 catch에서 처리되지 않은 모든 예외를 처리
try {
    // Code to try
} catch (IndexOutOfBoundsException eIndex) {
    System.out.println("Oops - wrong index");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops - String not a number");
} catch (Exception e) { // Handles all exceptions except the two above
    System.out.println("Something unplanned happened");
}
Java의 데이터 타입과 예외

finally

  • finally 블록의 코드는 항상 실행됨
// When exception happens
try {
    Integer.valueOf("one");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops");
} finally {
    System.out.println("Doing cleanup");
}
Oops
Doing cleanup

 

// When no exception gets thrown
try {
    Integer.valueOf("1");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops");
} finally {
    System.out.println("Doing cleanup");
}
Doing cleanup
Java의 데이터 타입과 예외

Exception 객체

  • Exception 객체에는 풍부한 정보가 담겨 있음
  • 메서드로 원인을 더 자세히 파악
    • .getMessage() 사람 읽기용 원인
    • .getClass() 예외 클래스/타입명
    • .printStackTrace() 스택 트레이스 출력(다음 슬라이드)
public class ExceptionExample {

    public static void main(String[] args) {
        try {
            Integer.valueOf("one");
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}
Java의 데이터 타입과 예외

예외 스택 트레이스

  • 스택 트레이스는 문제로 이어진 실행 흐름을 기록함
    • 아래: 이전 코드 예제의 출력(스택 트레이스 포함)
For input string: "one"
java.lang.NumberFormatException: For input string: "one"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:661)
    at java.base/java.lang.Integer.valueOf(Integer.java:988)
    at foo/exceptions.ExceptionExample.main(ExceptionExample.java:7)
Java의 데이터 타입과 예외

Ayo berlatih!

Java의 데이터 타입과 예외

Preparing Video For Download...