TestEx01.
package day10;
public class TestEx01 {
public void func() {
//변수는 트라이캐치 바깥에서 선언하기!
try {
//제어문 if for while
//메서드 호출
//객체 생성
}catch(Exception e) {
//예외 발생시 처리코드
}
}
public static void main(String[] args) {
try {
System.out.println(args[0]); //에러 발생
}catch(ArrayIndexOutOfBoundsException e) { //에러에 맞는 변수를 찾아서
System.out.println("인수를 입력 안하고 실행하셨습니다");//여기로 온다.
System.out.println(e);
}
}
}
TestEx03.
package day10;
public class TestEx03 {
public static void main(String[] args) {
int num = 100;
int result = 0;
for (int i = 0; i < 10; i++) { //트라이가 포문 안/밖 어디에 있는지 따라 또 결과가 다름
try {
//ArithmeticException: 랜덤 값이 0이 나오면 터지는 예외
result = num/ (int)(Math.random()*10);
System.out.println(result);
}catch(ArithmeticException e){ //이렇게 하면 프로그램이 뻑나는게 아니라 잘 실행되고 잘 끝남.
System.out.println("0 발생");
}
}
System.out.println("시스템 종료");
}
}
TestEx04.
package day10;
import java.util.Scanner;
public class TestEx04 {
public static void main(String[] args) {
//3개의 정수를 입력 받아 합을 구하는 프로그램 만들기
Scanner sc = new Scanner(System.in);
System.out.println("정수 3개 입력하세요> ");
int sum =0, n= 0;
for(int i = 0; i < 3; i++) {
System.out.println(i + ">>");
try {
n = Integer.parseInt(sc.nextLine());
}catch(NumberFormatException e) {
System.out.println("정수가 아닙니다. 다시 입력하세요");
i--;
continue;
}
sum += n;
}
System.out.println("합은: " + sum);
sc.close();
}
}
TestEx05.
package day10; //4. finally
public class TestEx05 {
public static void main(String[] args) {
System.out.println(1);
try {
System.out.println(2);
//System.out.println(0/0); //일부러 예외 발생 시키기
System.out.println(3); //0/0에서 예외가 발생해서 3 실행 안하고 바로 캐치로 점프
}catch(Exception e) {
System.out.println(4); //캐치로 오면 다시 트라이로 돌아갈 수 없음 for문이 아닌 이상
}finally {
System.out.println(5); //예외 발생 구문을 주석 처리하여 캐치가 실행 안되면 #3에서 바로 파이널리로
}
System.out.println(6);
}
}
TestEx06.
package day10; //5. 예외 발생 시키기
public class TestEx06 {
public static void main(String[] args) {
// try {
// //예외를 강제로 발생 시킴.
// throw new RuntimeException();
// }catch(Exception e) {
// System.out.println("예외가 발생했습니다.");
// }
try {
System.out.println("hello");
Exception e = new Exception ("고의로 예외를 발생시킴"); //exception 객체 생성
throw e;
}catch(Exception e){ //throw e가 값을 캐치 매개변수로 던져줌.
System.out.println(e.getMessage()); //메세지로 리턴해줌.
//System.out.println(e);
e.printStackTrace(); //예외 발생 시, 어디서 에러가 발생했는지 경로 추적할 수 있는 메세지 출력
//try-catch로 예외 처리 안하면 콘솔에 뜨는 메세지들을 (try-catch시 안나옴)
// 이 메서드를 통해 다시 출력할 수 있다.
}
}
}
TestEx07.
package day10;
public class TestEx07 {
public static void main(String[] args) {
try {
//Exception e = new Exception();
// NullPointerException e = new NullPointerException();
RuntimeException e = new RuntimeException();
throw e;
}catch(NullPointerException e) {
System.out.println("NullPointerException 예외 처리");
}catch(RuntimeException e) {
System.out.println("RuntimeException 예외 처리");
}
catch(Exception e) {
System.out.println("Exception 예외 처리");
}
}
}
TestEx08.
package day10; //throws
public class TestEx08 { //1번 해결법. 이렇게 하면 메인에서 트라이캐치문을 작성해야함.
static void method1() throws Exception {
method2();
}
// static void method1() { //2번 해결법
// try {
// method2();//부르는 쪽에서 예외처리를 해야함.
// //throw new Exception()의 예외를 이쪽으로 토스!
// } catch (Exception e) {
// e.printStackTrace(); //이렇게 하면 메인메서드는 메서드 호출만 하면 됨
// }
// }
static void method2() throws Exception { //발생하는 에러의 종류
throw new Exception(); //이 안에서 처리 안하고 날 부른쪽에서 토스할테니 예외처리를 해
}
// API 같은 경우는 실행하다가 예외가 발생할 수 있음. 예외는 API를 가져다가 쓰는
// 상황마다 다르게 처리해야 함. 가져다 쓰는 사람이 상황에 맞게 잘 예외 처리해라
// 난 기능 구현만 할거야.. 갖다 쓰다가 예외가 발생하면 쓰는 사람이 처리하셔
public static void main(String[] args) {
try {
method1();
} catch (Exception e) {
e.printStackTrace();
}
}
}
TestEx09.
package day10;
public class TestEx09 {
static void method1() throws Exception{
try {
throw new Exception();
}catch(Exception e) {
System.out.println("method1dptj 예외 처리");
throw e;
}
}
public static void main(String[] args) {
try {
method1();
} catch (Exception e) {
e.printStackTrace();
}
}
}
TestEx10.
package day10; //예외 처리를 이용한 약식 파일 만들기. 설치 프로그램. #06 참고.
class SpaceException extends Exception{
public SpaceException(String msg) {
super(msg); // Exception이 가진 (에러 메세지 받는) 부모 생성자 지정해서 호출
}
}
class MemoryException extends Exception{
public MemoryException(String msg) {
super(msg);
}
}
public class TestEx10 {
public static void main(String[] args) {
try {
startInstall(); //1 프로그램 시작 //4 에러 throw 이중에 맞는 에러 찾아 캐치
copyFiles();
} catch (SpaceException e) {
System.out.println("에러 메세지:" + e.getMessage());
System.out.println("설치 공간을 확보한 후 다시 설치하시기 바랍니다. ");
} catch (MemoryException e) {
System.out.println("에러 메세지:" + e.getMessage());
System.gc();
System.out.println("다시 설치하시기 바랍니다. ");
}finally {
deleteTempFiles(); //설치가 되든 안되든 임시 파일은 지워라
}
}
static void startInstall() throws SpaceException, MemoryException { //에러 던지기 스타트로 던짐.
if (!enoughSpace()) //2
throw new SpaceException("설치 공간이 부족합니다.");
//없는 예외처리 클래스. 우리가 원하는걸 만드는 거임
if(!enoughMemory()) //3
throw new MemoryException("메모리가 부족합니다. "
+ "다른 프로그램을 종료해주세요.");
}
static void copyFiles() {}
static void deleteTempFiles() {
System.out.println("임시 파일 삭제");
} //임시 파일 이용해서 설치하고 임시 파일은 제거하는
static boolean enoughSpace() { //설치할 수 있는 공간이 있는지
return true;}
static boolean enoughMemory() { //메모리 충분한지
return false;}
}