SlideShare a Scribd company logo
บทที่ 9
การจัด การกับ ข้อ ผิด พลาด
 (Exception Handling)

    อ.ธนิศ า เครือ ไวศยวรรณ
   คณะเทคโนโลยีส ารสนเทศ
สถาบัน เทคโนโลยีพ ระจอมเกล้า เจ้า
       คุณ ทหารลาดกระบัง
วัต ถุป ระสงค์
 แนะนำา ข้อ ผิด พลาดทีอ าจเกิด ขึ้น ได้ใ นภาษาจาวา
                       ่
 แนะนำา คลาสทีเ กี่ย วข้อ งกับ การจัด การกับ ข้อ ผิด
               ่
  พลาดทีก ำา หนดไว้ใ น Java API
            ่
 อธิบ ายคำา สัง ทีใ ช้ใ นการจัด การกับ ข้อ ผิด พลาดคือ
                ่ ่
  คำา สั่ง try,catch และ finally
 อธิบ ายกฎการจัด การกับ ข้อ ผิด พลาด

 แนะนำา วิธ ีก ารสร้า งคลาสประเภทข้อ ผิด พลาดขึ้น
 มาใหม่
ข้อ ผิด พลาด
 โปรแกรมภาษาจาวาแบ่ง ข้อ ผิด พลาดทีอ าจเกิด
                                    ่
 ขึ้น ขณะรัน โปรแกรมเป็น สอง ประเภทคือ
  •   Error   เป็น ข้อ ผิด พลาดที่ไ ม่ส ามารถแก้ไ ขและจัด การได้
      เช่น                 VirtualMachineError,OutOfMemoryError
  •   Exception   เป็น ข้อ ผิด พลาดที่ส ามารถแก้ไ ขหรือ จัด การ
      ได้ เช่น
       ArrayIndexOutOfBoundsException,FileNotFoundException

 ข้อ ผิด พลาดในภาษาจาวาจะกำา หนดเป็น ออปเจ็ค
 ของ คลาสต่า งๆ โดยมีค ลาส             Throwable   เป็น คลาส
 ราก
คลาสที่เ กี่ย วข้อ งกับ ข้อ ผิด พลาด
คลาสประเภท Exception
 Exception เป็น ข้อ ผิด พลาดทีเ กิด ในขณะรัน
                               ่
    โปรแกรมภาษาจาวา
 Exception        แบ่ง ออกเป็น สอง ประเภท คือ
     •   RuntimeException
     •   IOException
   RuntimeException เป็น ข้อ ผิด พลาดทีอ าจหลีก เลี่ย ง
                                        ่
    ได้ห ากมีก ารเขีย นโปรแกรมทีถ ูก ต้อ ง
                                    ่
   IOException   เป็น ข้อ ผิด พลาดทีภ าษาจาวากำา หนด
                                     ่
    ให้ต ้อ งมีก ารจัด การ หากมีก ารเรีย กใช้เ มธอดที่
    อาจเกิด ข้อ ผิด พลาดประเภทนีไ ด้   ้
คลาสประเภท Exception ที่ส ำา คัญ
        และพบบ่อ ย
   ArithmeticException
   ArrayIndexOutOfBoundsException
   EOFException
   FileNotFoundException
   InterruptedException
   IOException
   NullPointerException
   NumberFormatException
ตัว อย่า งโปรแกรมที่อ าจเกิด ข้อ ผิด
              พลาด
    public class ExceptionDemo {
     public class ExceptionDemo {
       public static void main(String args[]) {
        public static void main(String args[]) {
              System.out.println(args[2]);
               System.out.println(args[2]);
              System.out.println("Hello");
               System.out.println("Hello");
         }}
    }}
คำา สัง
                      ่   try..catch

 ภาษาจาวามีค ีย เ วิร ์ด try
                 ์         ทีเ ป็น คำา สัง ทีใ ช้ใ นการ
                               ่         ่ ่
 จัด การกับ เมธอดหรือ คำา สั่ง ทีอ าจเกิด ข้อ ผิด พลาด
                                 ่
 ซึ่ง จะส่ง ออปเจ็ค ประเภท Exception ในขณะรัน
 โปรแกรม
 รูป แบบ
            try {
                 [statements]
            }
 โปรแกรมภาษาจาวาจะสั่ง งานชุด คำา สั่ง ทีอ ยูใ น
                                          ่ ่
 บล็อ กทีล ะคำา สัง และหากเกิด ข้อ ผิด พลาดขึน ในคำา
                  ่                          ้
 สั่ง ประเภทใดก็จ ะมีก ารส่ง ออปเจ็ค ของข้อ ผิด
 พลาดประเภท Exception นัน ขึน มา
                               ้ ้
คำำ สัง
                      ่   try..catch

 ในกรณีท ต ้อ งกำรจัด กำรกับ ข้อ ผิด พลำดทีเ กิด ขึ้น
          ี่                                ่
 โปรแกรมจะต้อ งมีช ุด คำำ สั่ง อยูใ นบล็อ กของ
                                      ่
 คีย เ วิร ์ด catch ที่จ ะระบุช นิด ของออปเจ็ค ในคลำส
     ์
 ประเภท Exception ทีต ้อ งกำรจัด กำร
                             ่
 รูป แบบ

            catch(ExceptionType argumentName){
                 [statements]
            }
ตัว อย่ำ งโปรแกรมที่ม ีก ำรจัด กำร
          กับ ข้อ ผิด พลำด
public class ExceptionHandlingDemo {
 public class ExceptionHandlingDemo {
   public static void main(String args[]) {
    public static void main(String args[]) {
          try {
           try {
                 System.out.println(args[2]);
                  System.out.println(args[2]);
          } catch(ArrayIndexOutOfBoundsException ex) {
           } catch(ArrayIndexOutOfBoundsException ex) {
                   System.out.println("There is no third command
                    System.out.println("There is no third command
                   line argument");
                    line argument");
          }}
     }}
}}
กำรจัด กำรกับ ข้อ ผิด พลำดหลำยๆ
            ประเภท
 โปรแกรมภำษำจำวำสำมำรถจะมีช ุด คำำ สัง ของ
                                      ่
 บล็อ ก catch ได้ม ำกกว่ำ หนึง ชุด สำำ หรับ ในแต่ล ะ
                             ่
 บล็อ กคำำ สั่ง try
 ชนิด ของออปเจ็ค ประเภท         Exception ทีอ ยูใ นชุด
                                               ่ ่
 คำำ สั่ง ของบล็อ ก   catch   จะต้อ งเรีย งตำมลำำ ดับ กำร
 สืบ ทอด
 ในกรณีท ม ข ้อ ผิด พลำดเกิด ขึ้น
          ี่ ี                  ภำษำจำวำจะ
 พิจ ำรณำว่ำ เป็น ข้อ ผิด พลำดชนิด ใด ซึ่ง กำรทีจ ะ
                                                ่
 จัด กำรกับ ออปเจ็ค ประเภท Exception นัน จะ ้
 พิจ ำรณำจำกคลำสทีม ก ำรสืบ ทอดตำมลำำ ดับ ชั้น
                        ่ ี
ตัว อย่ำ งโปรแกรม
public class ExceptionHandlingDemoV2 {
 public class ExceptionHandlingDemoV2 {
   public static void main(String args[]) {
    public static void main(String args[]) {
          try {
           try {
                   int i = Integer.parseInt(args[0]);
                    int i = Integer.parseInt(args[0]);
                   System.out.println(4 / i);
                    System.out.println(4 / i);
          } catch(ArithmeticException ex) {
           } catch(ArithmeticException ex) {
                 System.out.println(ex.toString());
                  System.out.println(ex.toString());
          } catch(NumberFormatException ex) {
           } catch(NumberFormatException ex) {
                 System.out.println("Invalid numeric format");
                  System.out.println("Invalid numeric format");
          }}
     }}
}}
ตัว อย่ำ งโปรแกรมที่ไ ม่ถ ูก ต้อ ง
public class ExceptionHandlingDemoV3 {
 public class ExceptionHandlingDemoV3 {
   public static void main(String args[]) {
    public static void main(String args[]) {
          try {
           try {
                   int i = Integer.parseInt(args[0]);
                    int i = Integer.parseInt(args[0]);
                   System.out.println(4 / i);
                    System.out.println(4 / i);
                 System.out.println(args[2]);
                  System.out.println(args[2]);
          } catch(RuntimeException ex) {
           } catch(RuntimeException ex) {
                 System.out.println(ex.toString());
                  System.out.println(ex.toString());
          } catch(ArrayIndexOutOfBoundsException ex) {
           } catch(ArrayIndexOutOfBoundsException ex) {
                   System.out.println("There is no third command
                    System.out.println("There is no third command
                   line argument");
                    line argument");
          }}
     }}
}}
บล็อ ก      finally

 ภำษำจำวำมีค ีย เ วิร ์ด finally
                 ์                  ทีจ ะมีช ุด คำำ สั่ง อยูใ น
                                      ่                     ่
  บล็อ กเพือ ระบุใ ห้โ ปรแกรมทำำ ชุด คำำ สัง ดัง กล่ำ ว
            ่                                  ่
  หลัง จำกสิน สุด กำรทำำ งำนของชุด คำำ สั่ง ในบล็อ ก
              ้
  try หรือ catch
 ภำษำจำวำ จะทำำ ชุด คำำ สั่ง ในบล็อ ก finally เสมอ
  แม้ว ่ำ จะมีคำำ สัง return ในบล็อ ก try หรือ catch
                    ่
  ก่อ นก็ต ำม กรณีเ ดีย วทีจ ะไม่ท ำำ ชุด คำำ สั่ง ในบล็อ ก
                              ่
  finally คือ มีคำำ สั่ง System.exit();
ตัว อย่ำ งโปรแกรม
public class FinallyDemo {
 public class FinallyDemo {
   public static void main(String args[]) {
    public static void main(String args[]) {
          try {
           try {
                   System.out.println(args[2]);
                    System.out.println(args[2]);
                   System.out.println("Hello");
                    System.out.println("Hello");
          } catch(ArrayIndexOutOfBoundsException ex) {
           } catch(ArrayIndexOutOfBoundsException ex) {
                 System.out.println("There is no third argument");
                  System.out.println("There is no third argument");
          } finally {
           } finally {
                 System.out.println("Finish running the program");
                  System.out.println("Finish running the program");
          }}
     }}
}}
ตัว อย่ำ งโปรแกรม
public class FinallyDemoV2 {{
 public class FinallyDemoV2
    public static void main(String args[]) {{
     public static void main(String args[])
          FinallyDemoV2 obj == new FinallyDemoV2();
           FinallyDemoV2 obj    new FinallyDemoV2();
          obj.myMethod(args);
           obj.myMethod(args);
     }}
     public int myMethod(String args[]) {{
      public int myMethod(String args[])
          try {{
           try
                   System.out.println(args[2]);
                    System.out.println(args[2]);
                   return 0;
                    return 0;
          }} catch(ArrayIndexOutOfBoundsException ex) {{
              catch(ArrayIndexOutOfBoundsException ex)
                  System.out.println("There is no third argument");
                   System.out.println("There is no third argument");
          }} finally {{
              finally
                  System.out.println("Finish running the program");
                   System.out.println("Finish running the program");
                   return 1;
                    return 1;
          }}
     }}
}}
การจัด การกับ เมธอดที่ส ง ออปเจ็ค
                         ่
       ประเภท Exception
 เราสามารถจะจัด การกับ ออปเจ็ค ของ     Exception
 โดยใช้ค ลาสทีเ ป็น superclass ของ Exception
                  ่
 นัน ได้ อาทิเ ช่น เราสามาร ถ จัด การกับ
   ้
 FileNotFoundException โดยใช้ IOException หรือ
 Exception แทนได้
 การจัด การกับ Exception      มีส อง แบบ คือ
  • ใช้ค ำา สั่ง try/catch
  • ใช้ค ำา สั่ง throws ในการประกาศเมธอดที่จ ะมีก ารเรีย ก
   ใช้เ มธอดใดๆที่อ าจส่ง
   ออปเจ็ค ประเภท Exception
คำา สั่ง   throws

 รูป แบบการใช้ค ำา สัง throws
                      ่          มีด ัง นี้
     [modifier] return_type methodName([arguments]) throws
                           ExceptionType[,ExceptionType2] {
           ...
     }

 ตัว อย่า ง
     public void openfile(String s) throws
                           FileNotFoundException {
           ...
     }
คำา สั่ง   throws

 เมธอดใดๆสามารถทีจ ะจัด การ กับ Exception
                          ่                         โดย
  ใช้ค ำา สัง throws ได้ม ากกว่า หนึง ประเภท
            ่                       ่
 ตัว อย่า ง
     public void openFile(String s)throws
           FileNotFoundException,UnknownHostException {
                 ...
      }

 กรณีท ม ก ารใช้ค ำา สั่ง throws ส่ง ต่อ ไปเรื่อ ยๆ แล้ว
         ี่ ี
  เมธอด main() ซึ่ง เรีย กใช้เ มธอดสุด ท้า ยทีใ ช้ค ำา สัง
                                                  ่       ่
  throws ไม่ม ก ารจัด การกับ ออปเจ็ค ประเภท
              ี
  Exception ดัง กล่า ว โปรแกรมจะเกิด ข้อ ผิด
  พลาดในขั้น ตอนการรัน โปรแกรม เมือ มีข ้อ ผิด
                                   ่
ตัว อย่า งโปรแกรมทีไ ม่ม ีก ารจัด การ
                    ่
           กับ Exception
  public class ExceptionDemo1 {
   public class ExceptionDemo1 {
         public static void main(String args[]) {
          public static void main(String args[]) {
                 ExceptionDemo1 ex1 = new ExceptionDemo1();
                  ExceptionDemo1 ex1 = new ExceptionDemo1();
                 ex1.method1();
                  ex1.method1();
         }}
         public void method1() throws ArithmeticException {
          public void method1() throws ArithmeticException {
                 method2();
                  method2();
         }}
         public void method2() throws ArithmeticException {
          public void method2() throws ArithmeticException {
                 System.out.println(2/0);
                  System.out.println(2/0);
         }}
  }}
กฎ ของการกำา หนดเมธอดแบบ
           overriden
 เมธอดแบบ  overriden จะไม่อ นุญ าตให้ม ก ารจัด
                                           ี
 การออปเจ็ค ประเภท Exception โดยใช้ค ำา สัง    ่
 throws มากชนิด กว่า ทีเ มธอดเดิม จัด การอยูไ ด้
                       ่                     ่
ตัว อย่า งโปรแกรม ที่ม ีเ มธอดแบบ
      overriden ทีถ ูก ต้อ ง
                  ่
import java.io.*;
 import java.io.*;

public class Parent {
 public class Parent {
        public void myMethods() throws IOException { }
         public void myMethods() throws IOException { }
}}
___________________________________________________________
 ___________________________________________________________

public class OverrideException extends Parent{
 public class OverrideException extends Parent{
        public void myMethods() throws IOException {
         public void myMethods() throws IOException {
                new FileInputStream("temp.txt");
                 new FileInputStream("temp.txt");
        }}
}}
ตัว อย่า งโปรแกรม ที่ม ีเ มธอดแบบ
     overriden ที่ไ ม่ถ ูก ต้อ ง
import java.io.*;
 import java.io.*;

public class Parent {
 public class Parent {
   public void myMethods() throws FileNotFoundException { }
    public void myMethods() throws FileNotFoundException { }
}}
__________________________________
__________________________________
public class OverrideExceptionV2 extends Parent {
 public class OverrideExceptionV2 extends Parent {
        public void myMethods() throws
         public void myMethods() throws
                        FileNotFoundException,IOException {
                         FileNotFoundException,IOException {
                new FileInputStream("temp.txt");
                 new FileInputStream("temp.txt");
        }}
}}
การสร้า งคลาสประเภท Exception
            ขึ้น ใหม่
 การสร้า งคลาสประเภท    Exception ขึ้น มาใหม่
 สามารถทำา ได้โ ดยนิย ามคลาสใดๆให้ส บ ทอดมา
                                       ื
 จากคลาสทีช ื่อ Exception
           ่
 โดยทัว ไปคลาสทีช ื่อ
       ่         ่  Exception จะมี
 constructor สองรูป แบบคือ
  •   public Exception()
  •   public Exception(String s)

 ดัง นั้น คลาสทีส บ ทอดมาจากคลาสทีช ื่อ Exception
                 ่ ื               ่
 ควรจะมี constructor ทัง สองแบบ โดยรูป แบบ
                            ้
 หนึง จะมี argument ทีม ช นิด ข้อ มูล เป็น String
    ่                   ่ ี
 และมีค ำา สัง แรกใน constructor เป็น คำา สั่ง
             ่
 super(s);
ตัว อย่า งคลาสประเภท Exception
          ที่ก ำา หนดขึ้น ใหม่
public class MyOwnException extends Exception {
 public class MyOwnException extends Exception {
       public MyOwnException (String s) {
        public MyOwnException (String s) {
              super(s);
               super(s);
       }}
}}
การเขีย นเมธอดเพือ ส่ง ออปเจ็ค
                    ่
       ประเภท Exception
 เมธอดทีต ้อ งการส่ง ออปเจ็ค ประเภท
         ่                                 Exception
 เมือ เกิด ข้อ ผิด พลาดขึ้น ในคำา สั่ง ใด จะต้อ งเรีย กใช้
    ่
 คำา สั่ง ทีช อ throw เพือ จะสร้า งออปเจ็ค ของคลาส
            ่ ื่         ่
 ประเภท Exception ขึ้น มา
 รูป แบบ
    throw new ExceptionType([arguments])
 นอกจากนีค ำา สัง ประกาศเมธอดนัน จะต้อ งมีค ำา สัง
          ้      ่              ้                 ่
 throws เพื่อ กำา หนดให้ค ำา สัง ในเมธอดอื่น ๆทีเ รีย ก
                               ่                ่
 ใช้เ มธอดนีต ้อ งเขีย นคำา สั่ง ในการจัด การกับ ข้อ ผิด
               ้
 พลาดนี้
ตัว อย่า ง คลาส             FileHandler

import java.io.*;
 import java.io.*;

public class FileHandler {
 public class FileHandler {
    public static void openFile(String filename) throws
     public static void openFile(String filename) throws
                                            MyOwnException {
                                             MyOwnException {
         File f = new File(filename);
          File f = new File(filename);
         if (!f.exists()) {
          if (!f.exists()) {
                throw new MyOwnException("File Not Found");
                 throw new MyOwnException("File Not Found");
         }}
    }}
}}
ตัว อย่า งโปรแกรมที่ม ีก ารจัด การ
          กับ ข้อ ผิด พลาด
public class FileOpener {
 public class FileOpener {
    public static void main (String args[]) {
     public static void main (String args[]) {
          try {
           try {
                   FileHandler.openFile(args[0]);
                    FileHandler.openFile(args[0]);
                   System.out.println("Open successful");
                    System.out.println("Open successful");
          } catch (MyOwnException ex) {
           } catch (MyOwnException ex) {
                 System.err.println(ex);
                  System.err.println(ex);
          }}
     }}
}}
สรุป เนื้อ หาของบท
 ข้อ ดีป ระเภทหนึ่ง ของภาษาจาวาคือ      เราสามารถ
    เขีย นโปรแกรมให้ม ก ารตรวจจับ และจัด การกับ ข้อ
                        ี
    ผิด พลาดทีอ าจเกิด ขึ้น ได้ โดยทีก ารทำา งานไม่ต อ ง
              ่                      ่               ้
    หยุด ลง
   Error เป็น ข้อ ผิด พลาดทีไ ม่ส ามารถแก้ไ ขและ
                             ่
  จัด การได้ ส่ว น Exception เป็น ข้อ ผิด พลาดที่
  สามารถแก้ไ ขหรือ จัด การได้
 คำา สั่ง try และ catch เป็น คำา สั่ง ทีใ ช้ใ นการตรวจจับ
                                         ่
  และจัด การกับ ข้อ ผิด พลาดทีอ าจเกิด ขึ้น ได้ โดย
                                   ่
  บล็อ กคำา สั่ง catch สามารถมีไ ด้ม ากกว่า หนึง บล็อ ก
                                                   ่
  สำา หรับ ในแต่ล ะบล็อ กคำา สั่ง try
 คำา สั่ง finally   เป็น คำา สั่ง ทีอ ยูต ่อ จากคำา สั่ง
                                     ่ ่                    try/catch
สรุป เนื้อ หาของบท
 คำา สั่ง throws
               จะใส่ไ ว้ต รงคำา สั่ง ประกาศเมธอด
  สำา หรับ เมธอดที่ย ง ไม่ต ้อ งการจัด การกับ ข้อ ผิด
                     ั
  พลาดแต่จ ะให้เ มธอดทีเ รีย ก ใช้เ มธอดนี้ เป็น ตัว
                             ่
  จัด การแทน
 เราสามารถสร้า งคลาสประเภท        Exception ชนิด
  ใหม่ข ึ้น ได้ โดยจะต้อ งสืบ ทอดมาจากคลาสที่ช อื่
  Exception และต้อ งมีก ารเรีย กใช้ Constructor
  ของคลาส Exception ด้ว ย
แบบฝึก หัด
 ข้อ ที่   1
    • ทดลองเขีย นโปรแกรมเพื่อ จัด การกับ ข้อ ผิด พลาด   อาทิ
     เช่น IOException
     ArrayIndexOutOfBoundsException

 ข้อ ที่   2
    • ทดลองเขีย นโปรแกรมเพื่อ สร้า งคลาสของข้อ ผิด พลาด
     ขึ้น มาใหม่ โดยยกตัว อย่า งโปรแกรม Account

More Related Content

What's hot (20)

PPTX
Php เงื่อนไขต่างๆ
Jaemjan Sriarunrasmee
 
PDF
พื้นฐานภาษาจาวา
Sarocha Makranit
 
PPT
พื้นฐานภาษาจาวา
Aeew Autaporn
 
PDF
พื้นฐานภาษาจาวา
JK133
 
PDF
7 2โครงสร้าง
Supaksorn Tatongjai
 
PDF
ความรู้เบื้องต้นภาษาจาวา
Thanachart Numnonda
 
PPT
Java Programming [8/12] : Arrays and Collection
IMC Institute
 
PDF
Java Programming: การเขียนโปรแกรมภาษาจาวาเชิงอ็อบเจกต์
Thanachart Numnonda
 
PDF
บทที่ 11 การดักจับข
Theeravaj Tum
 
PDF
โปรแกรมย่อยและฟังก์ชันมาตรฐาน
Prapatsorn Keawnoun
 
PPTX
Lab Computer Programming 1
Saranyu Srisrontong
 
PDF
59170259 ผลคุณี
Beam Suna
 
PPTX
คำสั่งควบคุมของโปรแกรม
Parn Nichakorn
 
PDF
น.ส.ศิริวิภา กาญจนาวิล-59170116-sec-1
หน่อย หน่อย
 
ODP
Python Course #1
Sarunyhot Suwannachoti
 
PDF
Java Programming: หลักการเชิงอ็อบเจกต์
Thanachart Numnonda
 
PPTX
เมธอด Method
tyt13
 
Php เงื่อนไขต่างๆ
Jaemjan Sriarunrasmee
 
พื้นฐานภาษาจาวา
Sarocha Makranit
 
พื้นฐานภาษาจาวา
Aeew Autaporn
 
พื้นฐานภาษาจาวา
JK133
 
7 2โครงสร้าง
Supaksorn Tatongjai
 
ความรู้เบื้องต้นภาษาจาวา
Thanachart Numnonda
 
Java Programming [8/12] : Arrays and Collection
IMC Institute
 
Java Programming: การเขียนโปรแกรมภาษาจาวาเชิงอ็อบเจกต์
Thanachart Numnonda
 
บทที่ 11 การดักจับข
Theeravaj Tum
 
โปรแกรมย่อยและฟังก์ชันมาตรฐาน
Prapatsorn Keawnoun
 
Lab Computer Programming 1
Saranyu Srisrontong
 
59170259 ผลคุณี
Beam Suna
 
คำสั่งควบคุมของโปรแกรม
Parn Nichakorn
 
น.ส.ศิริวิภา กาญจนาวิล-59170116-sec-1
หน่อย หน่อย
 
Python Course #1
Sarunyhot Suwannachoti
 
Java Programming: หลักการเชิงอ็อบเจกต์
Thanachart Numnonda
 
เมธอด Method
tyt13
 

Similar to Java Programming [9/12]: Exception Handling (13)

PPT
Java intro
zanotsuke
 
PPTX
Computer Programming 2.1
Saranyu Srisrontong
 
PPT
Computer Programming 2.2
Saranyu Srisrontong
 
PPTX
การเขียนคำสั่งควบคุมแบบมีทางเลือก.
Mink Kamolwan
 
PPT
Program Statement Structure พื้นฐานโครงสร้างประโยคคำสั่งภาษาโปรแกรมคอมพิวเตอร์
SasiNity
 
PPT
Java Programming [3/12]: Control Structures
IMC Institute
 
PDF
ฟังก์ชั่น Switch
เทวัญ ภูพานทอง
 
PDF
Java-Answer Chapter 05-06
Wongyos Keardsri
 
PPT
บทที่ 3 คำสั่งควบคุม ส่วนที่ 1
อัครเดช โพธิญาณ์
 
PDF
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
Finian Nian
 
PDF
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
Finian Nian
 
PPTX
การเขียนคำสั่งควบคุมแบบมีทางเลือก
Thanon Paktanadechanon
 
Java intro
zanotsuke
 
Computer Programming 2.1
Saranyu Srisrontong
 
Computer Programming 2.2
Saranyu Srisrontong
 
การเขียนคำสั่งควบคุมแบบมีทางเลือก.
Mink Kamolwan
 
Program Statement Structure พื้นฐานโครงสร้างประโยคคำสั่งภาษาโปรแกรมคอมพิวเตอร์
SasiNity
 
Java Programming [3/12]: Control Structures
IMC Institute
 
ฟังก์ชั่น Switch
เทวัญ ภูพานทอง
 
Java-Answer Chapter 05-06
Wongyos Keardsri
 
บทที่ 3 คำสั่งควบคุม ส่วนที่ 1
อัครเดช โพธิญาณ์
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
Finian Nian
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
Finian Nian
 
การเขียนคำสั่งควบคุมแบบมีทางเลือก
Thanon Paktanadechanon
 
Ad

More from IMC Institute (20)

PDF
นิตยสาร Digital Trends ฉบับที่ 14
IMC Institute
 
PDF
Digital trends Vol 4 No. 13 Sep-Dec 2019
IMC Institute
 
PDF
บทความ The evolution of AI
IMC Institute
 
PDF
IT Trends eMagazine Vol 4. No.12
IMC Institute
 
PDF
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
IMC Institute
 
PDF
IT Trends 2019: Putting Digital Transformation to Work
IMC Institute
 
PDF
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
IMC Institute
 
PDF
IT Trends eMagazine Vol 4. No.11
IMC Institute
 
PDF
แนวทางการทำ Digital transformation
IMC Institute
 
PDF
บทความ The New Silicon Valley
IMC Institute
 
PDF
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10
IMC Institute
 
PDF
แนวทางการทำ Digital transformation
IMC Institute
 
PDF
The Power of Big Data for a new economy (Sample)
IMC Institute
 
PDF
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
IMC Institute
 
PDF
IT Trends eMagazine Vol 3. No.9
IMC Institute
 
PDF
Thailand software & software market survey 2016
IMC Institute
 
PPTX
Developing Business Blockchain Applications on Hyperledger
IMC Institute
 
PDF
Digital transformation @thanachart.org
IMC Institute
 
PDF
บทความ Big Data จากบล็อก thanachart.org
IMC Institute
 
PDF
กลยุทธ์ 5 ด้านกับการทำ Digital Transformation
IMC Institute
 
นิตยสาร Digital Trends ฉบับที่ 14
IMC Institute
 
Digital trends Vol 4 No. 13 Sep-Dec 2019
IMC Institute
 
บทความ The evolution of AI
IMC Institute
 
IT Trends eMagazine Vol 4. No.12
IMC Institute
 
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
IMC Institute
 
IT Trends 2019: Putting Digital Transformation to Work
IMC Institute
 
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
IMC Institute
 
IT Trends eMagazine Vol 4. No.11
IMC Institute
 
แนวทางการทำ Digital transformation
IMC Institute
 
บทความ The New Silicon Valley
IMC Institute
 
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10
IMC Institute
 
แนวทางการทำ Digital transformation
IMC Institute
 
The Power of Big Data for a new economy (Sample)
IMC Institute
 
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
IMC Institute
 
IT Trends eMagazine Vol 3. No.9
IMC Institute
 
Thailand software & software market survey 2016
IMC Institute
 
Developing Business Blockchain Applications on Hyperledger
IMC Institute
 
Digital transformation @thanachart.org
IMC Institute
 
บทความ Big Data จากบล็อก thanachart.org
IMC Institute
 
กลยุทธ์ 5 ด้านกับการทำ Digital Transformation
IMC Institute
 
Ad

Java Programming [9/12]: Exception Handling

  • 1. บทที่ 9 การจัด การกับ ข้อ ผิด พลาด (Exception Handling) อ.ธนิศ า เครือ ไวศยวรรณ คณะเทคโนโลยีส ารสนเทศ สถาบัน เทคโนโลยีพ ระจอมเกล้า เจ้า คุณ ทหารลาดกระบัง
  • 2. วัต ถุป ระสงค์  แนะนำา ข้อ ผิด พลาดทีอ าจเกิด ขึ้น ได้ใ นภาษาจาวา ่  แนะนำา คลาสทีเ กี่ย วข้อ งกับ การจัด การกับ ข้อ ผิด ่ พลาดทีก ำา หนดไว้ใ น Java API ่  อธิบ ายคำา สัง ทีใ ช้ใ นการจัด การกับ ข้อ ผิด พลาดคือ ่ ่ คำา สั่ง try,catch และ finally  อธิบ ายกฎการจัด การกับ ข้อ ผิด พลาด  แนะนำา วิธ ีก ารสร้า งคลาสประเภทข้อ ผิด พลาดขึ้น มาใหม่
  • 3. ข้อ ผิด พลาด  โปรแกรมภาษาจาวาแบ่ง ข้อ ผิด พลาดทีอ าจเกิด ่ ขึ้น ขณะรัน โปรแกรมเป็น สอง ประเภทคือ • Error เป็น ข้อ ผิด พลาดที่ไ ม่ส ามารถแก้ไ ขและจัด การได้ เช่น VirtualMachineError,OutOfMemoryError • Exception เป็น ข้อ ผิด พลาดที่ส ามารถแก้ไ ขหรือ จัด การ ได้ เช่น ArrayIndexOutOfBoundsException,FileNotFoundException  ข้อ ผิด พลาดในภาษาจาวาจะกำา หนดเป็น ออปเจ็ค ของ คลาสต่า งๆ โดยมีค ลาส Throwable เป็น คลาส ราก
  • 4. คลาสที่เ กี่ย วข้อ งกับ ข้อ ผิด พลาด
  • 5. คลาสประเภท Exception  Exception เป็น ข้อ ผิด พลาดทีเ กิด ในขณะรัน ่ โปรแกรมภาษาจาวา  Exception แบ่ง ออกเป็น สอง ประเภท คือ • RuntimeException • IOException  RuntimeException เป็น ข้อ ผิด พลาดทีอ าจหลีก เลี่ย ง ่ ได้ห ากมีก ารเขีย นโปรแกรมทีถ ูก ต้อ ง ่  IOException เป็น ข้อ ผิด พลาดทีภ าษาจาวากำา หนด ่ ให้ต ้อ งมีก ารจัด การ หากมีก ารเรีย กใช้เ มธอดที่ อาจเกิด ข้อ ผิด พลาดประเภทนีไ ด้ ้
  • 6. คลาสประเภท Exception ที่ส ำา คัญ และพบบ่อ ย  ArithmeticException  ArrayIndexOutOfBoundsException  EOFException  FileNotFoundException  InterruptedException  IOException  NullPointerException  NumberFormatException
  • 7. ตัว อย่า งโปรแกรมที่อ าจเกิด ข้อ ผิด พลาด public class ExceptionDemo { public class ExceptionDemo { public static void main(String args[]) { public static void main(String args[]) { System.out.println(args[2]); System.out.println(args[2]); System.out.println("Hello"); System.out.println("Hello"); }} }}
  • 8. คำา สัง ่ try..catch  ภาษาจาวามีค ีย เ วิร ์ด try ์ ทีเ ป็น คำา สัง ทีใ ช้ใ นการ ่ ่ ่ จัด การกับ เมธอดหรือ คำา สั่ง ทีอ าจเกิด ข้อ ผิด พลาด ่ ซึ่ง จะส่ง ออปเจ็ค ประเภท Exception ในขณะรัน โปรแกรม  รูป แบบ try { [statements] }  โปรแกรมภาษาจาวาจะสั่ง งานชุด คำา สั่ง ทีอ ยูใ น ่ ่ บล็อ กทีล ะคำา สัง และหากเกิด ข้อ ผิด พลาดขึน ในคำา ่ ้ สั่ง ประเภทใดก็จ ะมีก ารส่ง ออปเจ็ค ของข้อ ผิด พลาดประเภท Exception นัน ขึน มา ้ ้
  • 9. คำำ สัง ่ try..catch  ในกรณีท ต ้อ งกำรจัด กำรกับ ข้อ ผิด พลำดทีเ กิด ขึ้น ี่ ่ โปรแกรมจะต้อ งมีช ุด คำำ สั่ง อยูใ นบล็อ กของ ่ คีย เ วิร ์ด catch ที่จ ะระบุช นิด ของออปเจ็ค ในคลำส ์ ประเภท Exception ทีต ้อ งกำรจัด กำร ่  รูป แบบ catch(ExceptionType argumentName){ [statements] }
  • 10. ตัว อย่ำ งโปรแกรมที่ม ีก ำรจัด กำร กับ ข้อ ผิด พลำด public class ExceptionHandlingDemo { public class ExceptionHandlingDemo { public static void main(String args[]) { public static void main(String args[]) { try { try { System.out.println(args[2]); System.out.println(args[2]); } catch(ArrayIndexOutOfBoundsException ex) { } catch(ArrayIndexOutOfBoundsException ex) { System.out.println("There is no third command System.out.println("There is no third command line argument"); line argument"); }} }} }}
  • 11. กำรจัด กำรกับ ข้อ ผิด พลำดหลำยๆ ประเภท  โปรแกรมภำษำจำวำสำมำรถจะมีช ุด คำำ สัง ของ ่ บล็อ ก catch ได้ม ำกกว่ำ หนึง ชุด สำำ หรับ ในแต่ล ะ ่ บล็อ กคำำ สั่ง try  ชนิด ของออปเจ็ค ประเภท Exception ทีอ ยูใ นชุด ่ ่ คำำ สั่ง ของบล็อ ก catch จะต้อ งเรีย งตำมลำำ ดับ กำร สืบ ทอด  ในกรณีท ม ข ้อ ผิด พลำดเกิด ขึ้น ี่ ี ภำษำจำวำจะ พิจ ำรณำว่ำ เป็น ข้อ ผิด พลำดชนิด ใด ซึ่ง กำรทีจ ะ ่ จัด กำรกับ ออปเจ็ค ประเภท Exception นัน จะ ้ พิจ ำรณำจำกคลำสทีม ก ำรสืบ ทอดตำมลำำ ดับ ชั้น ่ ี
  • 12. ตัว อย่ำ งโปรแกรม public class ExceptionHandlingDemoV2 { public class ExceptionHandlingDemoV2 { public static void main(String args[]) { public static void main(String args[]) { try { try { int i = Integer.parseInt(args[0]); int i = Integer.parseInt(args[0]); System.out.println(4 / i); System.out.println(4 / i); } catch(ArithmeticException ex) { } catch(ArithmeticException ex) { System.out.println(ex.toString()); System.out.println(ex.toString()); } catch(NumberFormatException ex) { } catch(NumberFormatException ex) { System.out.println("Invalid numeric format"); System.out.println("Invalid numeric format"); }} }} }}
  • 13. ตัว อย่ำ งโปรแกรมที่ไ ม่ถ ูก ต้อ ง public class ExceptionHandlingDemoV3 { public class ExceptionHandlingDemoV3 { public static void main(String args[]) { public static void main(String args[]) { try { try { int i = Integer.parseInt(args[0]); int i = Integer.parseInt(args[0]); System.out.println(4 / i); System.out.println(4 / i); System.out.println(args[2]); System.out.println(args[2]); } catch(RuntimeException ex) { } catch(RuntimeException ex) { System.out.println(ex.toString()); System.out.println(ex.toString()); } catch(ArrayIndexOutOfBoundsException ex) { } catch(ArrayIndexOutOfBoundsException ex) { System.out.println("There is no third command System.out.println("There is no third command line argument"); line argument"); }} }} }}
  • 14. บล็อ ก finally  ภำษำจำวำมีค ีย เ วิร ์ด finally ์ ทีจ ะมีช ุด คำำ สั่ง อยูใ น ่ ่ บล็อ กเพือ ระบุใ ห้โ ปรแกรมทำำ ชุด คำำ สัง ดัง กล่ำ ว ่ ่ หลัง จำกสิน สุด กำรทำำ งำนของชุด คำำ สั่ง ในบล็อ ก ้ try หรือ catch  ภำษำจำวำ จะทำำ ชุด คำำ สั่ง ในบล็อ ก finally เสมอ แม้ว ่ำ จะมีคำำ สัง return ในบล็อ ก try หรือ catch ่ ก่อ นก็ต ำม กรณีเ ดีย วทีจ ะไม่ท ำำ ชุด คำำ สั่ง ในบล็อ ก ่ finally คือ มีคำำ สั่ง System.exit();
  • 15. ตัว อย่ำ งโปรแกรม public class FinallyDemo { public class FinallyDemo { public static void main(String args[]) { public static void main(String args[]) { try { try { System.out.println(args[2]); System.out.println(args[2]); System.out.println("Hello"); System.out.println("Hello"); } catch(ArrayIndexOutOfBoundsException ex) { } catch(ArrayIndexOutOfBoundsException ex) { System.out.println("There is no third argument"); System.out.println("There is no third argument"); } finally { } finally { System.out.println("Finish running the program"); System.out.println("Finish running the program"); }} }} }}
  • 16. ตัว อย่ำ งโปรแกรม public class FinallyDemoV2 {{ public class FinallyDemoV2 public static void main(String args[]) {{ public static void main(String args[]) FinallyDemoV2 obj == new FinallyDemoV2(); FinallyDemoV2 obj new FinallyDemoV2(); obj.myMethod(args); obj.myMethod(args); }} public int myMethod(String args[]) {{ public int myMethod(String args[]) try {{ try System.out.println(args[2]); System.out.println(args[2]); return 0; return 0; }} catch(ArrayIndexOutOfBoundsException ex) {{ catch(ArrayIndexOutOfBoundsException ex) System.out.println("There is no third argument"); System.out.println("There is no third argument"); }} finally {{ finally System.out.println("Finish running the program"); System.out.println("Finish running the program"); return 1; return 1; }} }} }}
  • 17. การจัด การกับ เมธอดที่ส ง ออปเจ็ค ่ ประเภท Exception  เราสามารถจะจัด การกับ ออปเจ็ค ของ Exception โดยใช้ค ลาสทีเ ป็น superclass ของ Exception ่ นัน ได้ อาทิเ ช่น เราสามาร ถ จัด การกับ ้ FileNotFoundException โดยใช้ IOException หรือ Exception แทนได้  การจัด การกับ Exception มีส อง แบบ คือ • ใช้ค ำา สั่ง try/catch • ใช้ค ำา สั่ง throws ในการประกาศเมธอดที่จ ะมีก ารเรีย ก ใช้เ มธอดใดๆที่อ าจส่ง ออปเจ็ค ประเภท Exception
  • 18. คำา สั่ง throws  รูป แบบการใช้ค ำา สัง throws ่ มีด ัง นี้ [modifier] return_type methodName([arguments]) throws ExceptionType[,ExceptionType2] { ... }  ตัว อย่า ง public void openfile(String s) throws FileNotFoundException { ... }
  • 19. คำา สั่ง throws  เมธอดใดๆสามารถทีจ ะจัด การ กับ Exception ่ โดย ใช้ค ำา สัง throws ได้ม ากกว่า หนึง ประเภท ่ ่  ตัว อย่า ง public void openFile(String s)throws FileNotFoundException,UnknownHostException { ... }  กรณีท ม ก ารใช้ค ำา สั่ง throws ส่ง ต่อ ไปเรื่อ ยๆ แล้ว ี่ ี เมธอด main() ซึ่ง เรีย กใช้เ มธอดสุด ท้า ยทีใ ช้ค ำา สัง ่ ่ throws ไม่ม ก ารจัด การกับ ออปเจ็ค ประเภท ี Exception ดัง กล่า ว โปรแกรมจะเกิด ข้อ ผิด พลาดในขั้น ตอนการรัน โปรแกรม เมือ มีข ้อ ผิด ่
  • 20. ตัว อย่า งโปรแกรมทีไ ม่ม ีก ารจัด การ ่ กับ Exception public class ExceptionDemo1 { public class ExceptionDemo1 { public static void main(String args[]) { public static void main(String args[]) { ExceptionDemo1 ex1 = new ExceptionDemo1(); ExceptionDemo1 ex1 = new ExceptionDemo1(); ex1.method1(); ex1.method1(); }} public void method1() throws ArithmeticException { public void method1() throws ArithmeticException { method2(); method2(); }} public void method2() throws ArithmeticException { public void method2() throws ArithmeticException { System.out.println(2/0); System.out.println(2/0); }} }}
  • 21. กฎ ของการกำา หนดเมธอดแบบ overriden  เมธอดแบบ overriden จะไม่อ นุญ าตให้ม ก ารจัด ี การออปเจ็ค ประเภท Exception โดยใช้ค ำา สัง ่ throws มากชนิด กว่า ทีเ มธอดเดิม จัด การอยูไ ด้ ่ ่
  • 22. ตัว อย่า งโปรแกรม ที่ม ีเ มธอดแบบ overriden ทีถ ูก ต้อ ง ่ import java.io.*; import java.io.*; public class Parent { public class Parent { public void myMethods() throws IOException { } public void myMethods() throws IOException { } }} ___________________________________________________________ ___________________________________________________________ public class OverrideException extends Parent{ public class OverrideException extends Parent{ public void myMethods() throws IOException { public void myMethods() throws IOException { new FileInputStream("temp.txt"); new FileInputStream("temp.txt"); }} }}
  • 23. ตัว อย่า งโปรแกรม ที่ม ีเ มธอดแบบ overriden ที่ไ ม่ถ ูก ต้อ ง import java.io.*; import java.io.*; public class Parent { public class Parent { public void myMethods() throws FileNotFoundException { } public void myMethods() throws FileNotFoundException { } }} __________________________________ __________________________________ public class OverrideExceptionV2 extends Parent { public class OverrideExceptionV2 extends Parent { public void myMethods() throws public void myMethods() throws FileNotFoundException,IOException { FileNotFoundException,IOException { new FileInputStream("temp.txt"); new FileInputStream("temp.txt"); }} }}
  • 24. การสร้า งคลาสประเภท Exception ขึ้น ใหม่  การสร้า งคลาสประเภท Exception ขึ้น มาใหม่ สามารถทำา ได้โ ดยนิย ามคลาสใดๆให้ส บ ทอดมา ื จากคลาสทีช ื่อ Exception ่  โดยทัว ไปคลาสทีช ื่อ ่ ่ Exception จะมี constructor สองรูป แบบคือ • public Exception() • public Exception(String s)  ดัง นั้น คลาสทีส บ ทอดมาจากคลาสทีช ื่อ Exception ่ ื ่ ควรจะมี constructor ทัง สองแบบ โดยรูป แบบ ้ หนึง จะมี argument ทีม ช นิด ข้อ มูล เป็น String ่ ่ ี และมีค ำา สัง แรกใน constructor เป็น คำา สั่ง ่ super(s);
  • 25. ตัว อย่า งคลาสประเภท Exception ที่ก ำา หนดขึ้น ใหม่ public class MyOwnException extends Exception { public class MyOwnException extends Exception { public MyOwnException (String s) { public MyOwnException (String s) { super(s); super(s); }} }}
  • 26. การเขีย นเมธอดเพือ ส่ง ออปเจ็ค ่ ประเภท Exception  เมธอดทีต ้อ งการส่ง ออปเจ็ค ประเภท ่ Exception เมือ เกิด ข้อ ผิด พลาดขึ้น ในคำา สั่ง ใด จะต้อ งเรีย กใช้ ่ คำา สั่ง ทีช อ throw เพือ จะสร้า งออปเจ็ค ของคลาส ่ ื่ ่ ประเภท Exception ขึ้น มา  รูป แบบ throw new ExceptionType([arguments])  นอกจากนีค ำา สัง ประกาศเมธอดนัน จะต้อ งมีค ำา สัง ้ ่ ้ ่ throws เพื่อ กำา หนดให้ค ำา สัง ในเมธอดอื่น ๆทีเ รีย ก ่ ่ ใช้เ มธอดนีต ้อ งเขีย นคำา สั่ง ในการจัด การกับ ข้อ ผิด ้ พลาดนี้
  • 27. ตัว อย่า ง คลาส FileHandler import java.io.*; import java.io.*; public class FileHandler { public class FileHandler { public static void openFile(String filename) throws public static void openFile(String filename) throws MyOwnException { MyOwnException { File f = new File(filename); File f = new File(filename); if (!f.exists()) { if (!f.exists()) { throw new MyOwnException("File Not Found"); throw new MyOwnException("File Not Found"); }} }} }}
  • 28. ตัว อย่า งโปรแกรมที่ม ีก ารจัด การ กับ ข้อ ผิด พลาด public class FileOpener { public class FileOpener { public static void main (String args[]) { public static void main (String args[]) { try { try { FileHandler.openFile(args[0]); FileHandler.openFile(args[0]); System.out.println("Open successful"); System.out.println("Open successful"); } catch (MyOwnException ex) { } catch (MyOwnException ex) { System.err.println(ex); System.err.println(ex); }} }} }}
  • 29. สรุป เนื้อ หาของบท  ข้อ ดีป ระเภทหนึ่ง ของภาษาจาวาคือ เราสามารถ เขีย นโปรแกรมให้ม ก ารตรวจจับ และจัด การกับ ข้อ ี ผิด พลาดทีอ าจเกิด ขึ้น ได้ โดยทีก ารทำา งานไม่ต อ ง ่ ่ ้ หยุด ลง  Error เป็น ข้อ ผิด พลาดทีไ ม่ส ามารถแก้ไ ขและ ่ จัด การได้ ส่ว น Exception เป็น ข้อ ผิด พลาดที่ สามารถแก้ไ ขหรือ จัด การได้  คำา สั่ง try และ catch เป็น คำา สั่ง ทีใ ช้ใ นการตรวจจับ ่ และจัด การกับ ข้อ ผิด พลาดทีอ าจเกิด ขึ้น ได้ โดย ่ บล็อ กคำา สั่ง catch สามารถมีไ ด้ม ากกว่า หนึง บล็อ ก ่ สำา หรับ ในแต่ล ะบล็อ กคำา สั่ง try  คำา สั่ง finally เป็น คำา สั่ง ทีอ ยูต ่อ จากคำา สั่ง ่ ่ try/catch
  • 30. สรุป เนื้อ หาของบท  คำา สั่ง throws จะใส่ไ ว้ต รงคำา สั่ง ประกาศเมธอด สำา หรับ เมธอดที่ย ง ไม่ต ้อ งการจัด การกับ ข้อ ผิด ั พลาดแต่จ ะให้เ มธอดทีเ รีย ก ใช้เ มธอดนี้ เป็น ตัว ่ จัด การแทน  เราสามารถสร้า งคลาสประเภท Exception ชนิด ใหม่ข ึ้น ได้ โดยจะต้อ งสืบ ทอดมาจากคลาสที่ช อื่ Exception และต้อ งมีก ารเรีย กใช้ Constructor ของคลาส Exception ด้ว ย
  • 31. แบบฝึก หัด  ข้อ ที่ 1 • ทดลองเขีย นโปรแกรมเพื่อ จัด การกับ ข้อ ผิด พลาด อาทิ เช่น IOException ArrayIndexOutOfBoundsException  ข้อ ที่ 2 • ทดลองเขีย นโปรแกรมเพื่อ สร้า งคลาสของข้อ ผิด พลาด ขึ้น มาใหม่ โดยยกตัว อย่า งโปรแกรม Account