IT/Java

자바 try, catch, finally, exception

노마드오브 2018. 8. 5. 21:39

package test;


class MyDate {

int year = 2018;

}


public class Test1 {


public static void main(String[] args) {

System.out.println("==시작==");

MyDate myDate = null;

try {

System.out.println(myDate.year);

} catch (Exception e) {

System.out.println("예외발생");

System.out.println(e);

System.out.println(e.toString());

System.out.println(e.getMessage());

e.printStackTrace();

}


System.out.println("==종료==");

} // main()


}




package test;

public class Test2 {

public static void main(String[] args) {
System.out.println("==시작==");
int[] num = {1, 2, 3};
// alt shift z y
try {
num[10] = 5;
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("==종료==");
} // main()

}



package test;

import java.util.List;

public class Test3 {

void methodA() throws Exception {
System.out.println("methodA() 시작");
methodB();
System.out.println("methodA() 종료");
}
void methodB() throws RuntimeException {
System.out.println("methodB() 시작");
methodC();
System.out.println("methodB() 종료");
} // methodB()

void methodC() throws ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException {
System.out.println("methodC() 시작");
int num = 0;
int result = 10 / num;  // 0으로 나눔
List list = null;
list.add("문자열");  // 널포인터 예외
int[] arr = {1, 2, 3};
arr[5] = 10;  // 인덱스범위초과 예외
System.out.println("methodC() 종료");
} // methodC()
public static void main(String[] args) {
System.out.println("main() 시작");
Test3 t = new Test3();
try {
t.methodA();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("main() 종료");
} // main()

}



package test;

import java.util.Scanner;

class Dog {
int age;

public void setAge(int age) throws Exception {
System.out.println("age = " + age);
if (age < 0) {
// 예외를 인위적으로 발생
throw new Exception("age값이 0보다 작습니다.");
}
}

public int getAge() {
// try-catch-finally에서 catch블록이 있으면 예외처리가 목적임.
// try-finally 예외처리가 목적이 아님!

Scanner scanner = new Scanner(System.in);
try {
return age;
} finally {
System.out.println("finally 블록");
scanner.close();
}
} // getAge();
}

public class Test4 {

public static void main(String[] args) {
System.out.println("main() 시작");
Dog dog = new Dog();
try {
dog.setAge(-5);
} catch (Exception e) {
e.printStackTrace();
}

System.out.println(dog.getAge());
System.out.println("main() 종료");
} // main()

}