자바네트워크프로그래밍 (OCJP 국제공인자격취득중심 ) 충북대학교 최민
기본예제 예외클래스를정의하고사용하는예제 class NewException extends Exception { public class ExceptionTest { static void methoda() throws NewException { System.out.println("NewException 예외를던집니다."); throw new NewException(); public static void main(string[] args) { NewException ne = new NewException(); try { System.out.println("methodA() 를실행합니다."); methoda(); System.out.println(" 이문장이평가될까요?"); catch(newexception e) { System.out.println("NewException 예외를받았습니다."); System.out.println("try-catch 문을통과했습니다."); 2
기본예제 NewException Exception 클래스로부터상속 methoda() 는 throw 를통해서예외를던지겠다고출력한다음사용자정의예외인 NewException 를던짐. 예외를던지는문장또는발생시키는문장이포함된메소드에서는반드시예외처리를해주어야함. 이메소드에는 try{ catch{ 문이없기때문에 throws 키워드로예외를던져버림. 만약던지지않으면컴파일에러가발생함. 여기서던진예외는이메소드를호출하는메인메소드의 try{ catch{ 문으로처리하는데, 예외가던져지면예외가던져졌다고출력. 3
기본예제 실행결과 methoda() 문을실행합니다. NewException 예외를던집니다. NewException 예외를받았습니다. try-catch 문을통과했습니다. try 문에서예외를던지는 methoda() 가실행된다음문장은출력되지않음 예외가발생하면 try{ 블록의진행을멈추고 catch 블록으로진행되기때문. 4
기본예제 여러개의예외를던지는메소드 import java.io.*; class Exception0 extends Exception{ String s = "Exception0"; class Exception1 extends Exception0{ String s = "Exception1"; class TestException { static void methoda(int i) throws Exception0, Exception1{ if (i == 0){ throw new Exception0(); else if (i == 1){ throw new Exception1(); static void methodb() throws IOException{ throw new IOException(); 5
기본예제 public static void main(string[] args) { for (int i = 0; i <= 3; i++) { try{ System.out.println("i == " + i); methoda(i); // point x methodb(); catch (Exception1 e1) { System.out.println("catch : " + e1.s); catch (Exception0 e0) { System.out.println("catch : " + e0.s); catch (Exception e) { System.out.println("catch : Exception"); finally { System.out.println("finally"); 6
예제설명 1. methoda() 처럼메소드가던질수있는예외의수에는제한이없고, catch 문을순차적으로배치 예문의 System.out.println(e0.s) 처럼발생한예외객체의멤버들또한자유롭게이용할수있음 2. 다중예외를처리하는구문에서는하위예외객체부터먼저 catch 해주어야함 만약상위예외객체부터 catch 하는구문을만들면컴파일에러가발생함. 하위예외객체부터순차적으로 catch 하도록구문을변경해야함 7
예제설명 catch (Exception0 e0) { // Exception0 가상위예외 System.out.println("catch : " + e0.s); catch (Exception1 e1) { // Exception0 를상속받은예외 System.out.println("catch : " + e1.s); Exception0 -> Exception1 순서변경시에러발생 상위예외객체는하위예외객체도 catch 할수있기때문에, 상위예외객체를상위에선언하면, 아래의하위예외객체를선언하는것이무의미함. TestException.java:34: exception Exception1 has already been caught catch (Exception1 e1) { 8
예제설명 3. 선언한 catch 블록중에발생한에러와일치하는것이없을때, 모든예외클래스의상위클래스 Exception 은어떤예외라도처리 즉, 예제에서 methodb() 가 IOException 을발생시키면마지막 catch 블록이실행 출력결과 i == 0 catch : Exception0 finally i == 1 catch : Exception1 finally i == 2 catch : Exception finally i == 3 catch : Exception finally 9
문제 Which four types of objects can be thrown using the throw statement? (choose four) a) Error b) Event c) Object d) Exception e) Throwable f) RuntimeException 10
문제 import java.io.ioexception; public class ExceptionTest { public static void main(string[] args) { try { methoda(); catch(ioexception io) { System.out.println("caught IOException"); catch(exception e) { System.out.println("caught Exception"); static void methoda() throw new IOException() { what result? a) The code will not compile b) Output is "caught Exception" c) Output is "caught IOException" d) The program execute normally without print a message 11
ExceptionTest.java:14: ';' expected static void methoda() throw new IOException() { ^ ExceptionTest.java:14: missing method body, or declare abstract static void methoda() throw new IOException() { ^ 12
문제 import java.io.*; public class Test { static void method() throws EOFException { throw new EOFException(); public static void main(string args[]) { try { method( ); // point x catch (IOException e) { System.out.println ("IO"); catch (Exception e) { System.out.println("General"); finally { System.out.println ("Finally"); System.out.println ("Busy"); If EOFException is a sub class of IOException, what's the result? 13
문제 If EOFException is a sub class of IOException, what's the result? a) Compile error occur b) An Exception is thrown in // point x c) Finally Buse d) IO Finally Busy e) General Finally Busy 14
finally 사용법 finally 문 예외를처리하던처리하지않던간에무조건실행되는블록을정의 try{ // 예외를던질수있는문장들 catch( 예외참조 ) { // 예외를받고실행될문장들 finally{ // 무조건실행되는문장들 예외의발생여부와관계없이 finally 블록은항상실행. 15
finally 사용법 또한 break, return 등의메소드흐름중지문과만났을때에도 finally 블록은실행 finally 블록이실행되지않는경우는 try 블록이나 catch 블록에서시스템을강제종료 System.exit() 하는경우임. [ 주의 ] return, break 등의존재와무관하게 try 블록이실행되면 finally 블록도무조건실행. [ 주의 ] Finally 블록의내용은예외발생여부와관계없이항상수행 심지어 try 절또는 catch 절에 return 문이있더라도 finally 절의내용이수행된다음 return ( 단, System.exit( ) 문장이있는경우에는 finally 절을수행하지않고종료 ) 16
기본예제 Try 실행 -> catch 실행 -> finally 실행 public class MyExceptionTest { public static void main(string[] args) { NewException ne = new NewException(); try{ System.out.println("try :" + "excute methoda()"); ne.methoda(); catch(newexception e){ System.out.println("catch : caught"); finally{ System.out.println("finally"); System.out.println("out of try-catch"); 17
기본예제 class NewException extends Exception{ void methoda() throws NewException{ System.out.println("methodA() : " + "throw NewException"); throw new NewException(); 18
예제설명 try : excute methoda() methoda() : throw NewException catch : caught finally out of try-catch 19
기본예제 class NewException extends Exception{ void methoda(boolean f) throws NewException{ System.out.println("methodA() 가예외를던질까요?"); if (f == true){ System.out.println("methodA() 가예외를던집니다."); throw new NewException(); public class ExceptionTest { public static void main(string[] args) { NewException ne = new NewException(); try{ ne.methoda(false); System.out.println(" 이문장이실행된다면예외는던져지지않았습니다."); catch(newexception e){ System.out.println("catch : caught"); finally{ System.out.println("finally"); System.out.println("out of try-catch"); 20
예제설명 메소드에서예외가던져지지않았을때 try{ catch{ finally{ 문의실행순서 위의예제에서 methoda() 는 flag 가 true 일때만예외를던짐 false 를넘겨서예외를던지지않자, catch 문은실행되지않음. finally 문은실행되고있는데, 사실 finally 문은 catch 문의실행여부와관계없이프로그램이정상종료한다면어떤경우에도반드시실행됨 methoda() 가예외를던질까요? 이문장이실행된다면예외는던져지지않았습니다. finally out of try-catch 21
문제 import java.io.ioexception; public class ExceptionTest{ static void methoda() { throw new IOException(); public static void main(string[] args) { try { methoda(); catch(ioexception e) { System.out.println("caught IOException"); What's the result? a) The code will not compile b) Output is "caught Exception" c) Output is "caught IOException" d) The program execute normally without print a message 22
ExceptionTest.java:5: unreported exception java.io.ioexception; must be caught or declared to be thrown throw new IOException(); ^ ExceptionTest.java:10: exception java.io.ioexception is never thrown in body of corresponding try statement catch(ioexception e) { ^ 23
문제 public class Foo{ public static void main(string[] args) { try { return; finally { System.out.println("Finally"); What's the result? a) Print nothing b) Print "Finally" c) Not compiled and will Exception thrown d) Not compiled because catch block missing 24
관련문제 public class Foo{ public static void main(string[] args) { try { System.exit(0); finally { System.out.println("Finally"); What's the result? a) Print nothing b) Print "Finally" c) Not compiled and will Exception thrown d) Not compiled because catch block missing 25