296p. 에제 8-1~2
//try-catch문1
class Ex_JS {
public static void main(String args[]) {
System.out.println(1); //정상출력
try {
System.out.println(2); //정상출력
System.out.println(3); //정상출력
} catch (ArithmeticException ae) {
System.out.println(4);
//try문에 에러가 있을 시 실행되는 문장인데 에러가 없으므로 출력안됨
}
System.out.println(5); //정상출력
}
}
출력값:
1
2
3
5
//try-catch문2
class Ex_JS {
public static void main(String args[]) {
System.out.println(1); //정상출력
try {
System.out.println(0/0); //에러발생
System.out.println(2); //catch문으로 해결하기 전이므로 실행되지 않는다.
} catch (ArithmeticException ae) {
System.out.println(3); //예외가 발생했으므로 catch문의 문장이 수행됨
}
System.out.println(4); //정상출력
}
}
출력값:
1
3
4
297p. 에제 8-3~4
//예외의 발생과 catch블럭1
class Ex_JS {
public static void main(String args[]) {
System.out.println(1);
System.out.println(2);
try {
System.out.println(3);
System.out.println(0/0);
System.out.println(4);
} catch (Exception e) { //모든 예외의 조상클래스
System.out.println(5);
}
System.out.println(6);
}
}
출력값:
1
2
3
5
6
//예외의 발생과 catch블럭2
class Ex_JS {
public static void main(String args[]) {
System.out.println(1);
System.out.println(2);
try {
System.out.println(3);
System.out.println(0/0); //ArithmeticException 발생
System.out.println(4);
} catch (ArithmeticException ae) {
if (ae instanceof ArithmeticException)
System.out.println("true");
System.out.println("ArithmeticException");
} catch (Exception e) {
System.out.println("Exception");
//ArithmeticException을 제외한 모든 예외가 처리된다.
}
System.out.println(6);
}
}
출력값:
1
2
3
true
ArithmeticException
6
299p. 에제 8-5
//printStackTrace()와 getMessage()
class Ex_JS {
public static void main(String args[]) {
System.out.println(1);
System.out.println(2);
try {
System.out.println(3);
System.out.println(0/0);
System.out.println(4);
} catch (ArithmeticException ae) {
ae.printStackTrace();
//예외발생 당시 호출스택에 있던 메서드 정보, 예외 메세지를 화면에 출력한다.
System.out.println("예외메세지 : "+ ae.getMessage());
//ArithmeticException인스턴스에 저장된 메세지를 알 수 있다.
}
System.out.println(6);
}
}
출력값:
1
2
3
java.lang.ArithmeticException: / by zero
at Ex_JS.main(Ex_JS.java:9)
예외메세지 : / by zero
6
299p. 에제 8-6
//예외 발생시키기
class Ex_JS {
public static void main(String args[]) {
try {
Exception e = new Exception("고의로 발생시켰음.");
throw e; //고의로 예외를 발생시킴
// throw new Exception("고의로 발생시켰음.");
} catch (Exception e) {
System.out.println("에러 메세지 : "+ e.getMessage());
//발생한 예외클래스의 인스턴스에 저장된 메세지가 출력
e.printStackTrace();
}
System.out.println("프로그램이 정상 종료되었음.");
}
}
출력값:
에러 메세지 : 고의로 발생시켰음.
java.lang.Exception: 고의로 발생시켰음.
at Ex_JS.main(Ex_JS.java:5)
프로그램이 정상 종료되었음.
304p. 에제 8-9
//메서드에 예외 선언하기1
class Ex_JS {
public static void main(String[] args) throws Exception {
method1(); //같은 클래스 내 static멤버이므로 객체생성없이 호출 가능
//메소드1을 호출, main 메서드에도 try-catch문이 없음-> 비정상 종료(JVM으로 넘어감)
}
static void method1() throws Exception {
method2(); //메소드2를 호출
}
static void method2() throws Exception {
throw new Exception(); //예외를 고의로 발생시킴
}
}
출력값:
Exception in thread "main" java.lang.Exception
at Ex_JS.method2(Ex_JS.java:13)
at Ex_JS.method1(Ex_JS.java:9)
at Ex_JS.main(Ex_JS.java:4)
//예외가 발생한 당시 정보를 담고있음
305p. 에제 8-10
//메서드에 예외 선언하기2
import java.io.*;
class Ex_JS {
public static void main(String[] args) {
try {
File f = createFile(args[0]);
System.out.println(f.getName()+"파일이 성공적으로 생성되었습니다.");
} catch (Exception e) {
System.out.println(e.getMessage()+"다시 입력해 주시기 바랍니다.");
}
}
static File createFile(String fileName) throws Exception {
if (fileName==null || fileName.equals(""))
throw new Exception("파일 이름이 유효하지 않습니다.");
File f = new File(fileName);
f.createNewFile();
return f; //예외는 여기서 발생하였지만 호출한 메서드가 처리하도록 넘긴다.
}
}
출력값:
test2.txt파일이 성공적으로 생성되었습니다.
파일 이름이 유효하지 않습니다.다시 입력해 주시기 바랍니다.
308p. 에제 8-11
//사용자 정의 예외 만들기
class Ex_JS {
public static void main(String argString[]) {
try {
startInstall();
copyFiles();
} catch (SpaceException e) {
System.out.println("에러 메세지 : " + e.getMessage());
e.printStackTrace();
System.out.println("공간을 확보한 후에 다시 설치하시기 바랍니다.");
} catch (MemoryException me) {
System.out.println("에러 메세지 : " + me.getMessage());
me.printStackTrace();
System.gc();
System.out.println("다시 설치를 시도하세요.");
} finally { //예외 발생여부 관계없이 항상 수행되어야하는 문장
deleteTempFiles();
}
}
static void startInstall() throws SpaceException, MemoryException {
if(!enoughSpace())
throw new SpaceException("설치할 공간이 부족합니다.");
if(!enoughMemory())
throw new MemoryException("메모리가 부족합니다.");
}
static void copyFiles() {}
static void deleteTempFiles() {}
static boolean enoughSpace() {
return false;
}
static boolean enoughMemory() {
return true;
}
}
class SpaceException extends Exception { //사용자 정의 예외1
SpaceException(String msg) {
super(msg);
}
}
class MemoryException extends Exception { //사용자 정의 예외2
MemoryException(String msg) {
super(msg);
}
}
출력값:
에러 메세지 : 설치할 공간이 부족합니다.
SpaceException: 설치할 공간이 부족합니다.
at Ex_JS.startInstall(Ex_JS.java:23)
at Ex_JS.main(Ex_JS.java:5)
공간을 확보한 후에 다시 설치하시기 바랍니다.
310p. 에제 8-12
//예외 던지기
class Ex_JS {
public static void main(String[] args) {
try {
method1(); //호출>예외발생
} catch (Exception e) {
System.out.println("main메서드에서 예외가 처리되었습니다.");
}
}
static void method1() throws Exception {
try {
throw new Exception(); //예외 발생
} catch (Exception e) {
System.out.println("method1메서드에서 예외가 처리되었습니다.");
throw e; //다시 예외를 발생시킴
}
}
}
출력값:
method1메서드에서 예외가 처리되었습니다.
main메서드에서 예외가 처리되었습니다.
314p. 에제 8-13
//연결된 예외
class Ex_JS {
public static void main(String args[]) {
try {
install();
} catch (InstallException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
static void install() throws InstallException {
try {
startInstall(); // 프로그램 설치에 필요한 준비를 한다.
copyFiles(); //파일들을 복사한다.
} catch (SpaceException2 e) {
InstallException ie = new InstallException("설치 중 예외발생");
ie.initCause(e);
throw ie;
} catch (MemoryException2 me) {
InstallException ie = new InstallException("설치 중 예외발생");
ie.initCause(me);
throw ie;
} finally {
deleteTempFiles();
}
}
static void startInstall() throws SpaceException2, MemoryException2{
if(!enoughSpace()) {
throw new SpaceException2("설치할 공간이 부족합니다.");
}
if (!enoughMemory()) {
throw new MemoryException2("메모리가 부족합니다.");
}
}
static void copyFiles() {}
static void deleteTempFiles() {}
static boolean enoughSpace() {
return false;
}
static boolean enoughMemory() {
return true;
}
}
class InstallException extends Exception {
InstallException(String msg) {
super(msg);
}
}
class SpaceException2 extends Exception {
SpaceException2(String msg) {
super(msg);
}
}
class MemoryException2 extends Exception {
MemoryException2(String msg) {
super(msg);
}
}
출력값:
InstallException: 설치 중 예외발생
at Ex_JS.install(Ex_JS.java:18)
at Ex_JS.main(Ex_JS.java:5)
Caused by: SpaceException2: 설치할 공간이 부족합니다.
at Ex_JS.startInstall(Ex_JS.java:32)
at Ex_JS.install(Ex_JS.java:15)
... 1 more