Java의 데이터 타입과 예외
Jim White
Java Developer
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
try {
// Statements to be executed and watched for exceptions
}
try {
// Statements to be executed and watched for exceptions
} catch (<Exception type> <variable name>) {
// Statements to execute if an exception has occurred
}
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
catch 블록으로 예외 유형별 처리catch는 고유한 예외 타입과 변수 사용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
catch (Exception 변수){ }로 전체 예외를 포괄 처리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");
}
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
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();
}
}
}
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의 데이터 타입과 예외