Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

การโยน Exception ใน Java: throw และ throws Keywords

Exceptions (ข้อยกเว้น) = เหตุการณ์ไม่คาดคิดระหว่างรันโปรแกรม เมื่อโค้ดเจอ exception โฟลว์โปรแกรมจะถูก terminate

สำคัญมากที่ต้องจัดการ exceptions ให้ถูกต้องใน Java ไม่เช่นนั้นโค้ดอาจหยุดระหว่างรัน ส่งผลต่อ user experience

นี่คือที่มาของคีย์เวิร์ด throw และ throws ใช้จัดการ exceptions ใน Java บทช่วยสอนนี้อธิบายการใช้งานพร้อมตัวอย่าง

Exceptions ใน Java

มี 2 เหตุการณ์กระทบโฟลว์โปรแกรม: Errors และ Exceptions

  1. Error: ปัญหาใน JVM เช่น memory leaks, หน่วยความจำหมด, library compatibility issues เมื่อเจอ error โปรแกรมกู้คืนยาก ปกติไมาจัดการในโค้ด
  2. Exception: จับและจัดการในโค้ดได้ เมื่อเจอ exception สร้าง exception object เก็บข้อมูล เช่น ชื่อ exception และตำแหน่งที่เกิด

สาเหตุ exceptions: ข้อผิดพลาดโค้ด, เปิดไฟล์ไม่มีอยู่, อินพุตผู้ใช้ผิด, ขาดการเชื่อมต่อเครือข่าย ฯลฯ

2 ประเภท exceptions ที่ควรรู้:

  • Unchecked exceptions: เช็คที่ runtime เช่น ArithmeticException, ArrayIndexOutOfBoundsException
  • Checked exceptions: เช็คที่ compile-time เช่น IOException, InterruptedException

ส่วนใหญ่ควรจัดการ checked exceptions เพราะ unchecked exceptions มักมาจาก programming errors มากกว่า unexpected behavior

คีย์เวิร์ด Throws ใน Java

throws ใช้ประกาศประเภท exceptions ที่อาจเกิดในบล็อกโค้ด ไวยากรณ์:

accessModifier return functionName() throws Exception1, Exception2 { 
    // Run code 
}

ตัวอย่าง: เช็คอายุลูกค้าดูหนัง

โปรแกรมโรงภาพยนตร์ เช็คอายุลูกค้าดูหนัง 16+ อายุ < 16 -> ไม่อนุญาต 16 ขึ้นไป -> อนุญาต ใช้ throws ArithmeticException

class Main { 
    public static void verifyAge(int age) throws ArithmeticException { 
        if (age < 16) { 
            throw new ArithmeticException("This customer is not old enough to see the movie."); 
        } else { 
            System.out.println("This customer is old enough to see the movie."); 
        } 
    } 
    public static void main(String[] args) { 
        verifyAge(14); 
    } 
}

ผลลัพธ์: Exception in thread "main" java.lang.ArithmeticException: This customer is not old enough to see the movie.

อายุ 14 < 16 -> verifyAge() รัน -> age < 16 เป็น true -> throw ArithmeticException throws ประกาศประเภท exception ที่ verifyAge() อาจโยน throw โยน exception จริงในโปรแกรม

คีย์เวิร์ด Throw ใน Java

throw ใช้โยน exception เดียวในโค้ด ตามด้วย object ที่จะโยน ไวยากรณ์: throw throwObject;

โยน Checked Exception (IOException)

อยากให้พิมพ์ "This file does not exist." เมื่อเจอ IOException (checked exception)

import java.io.*; 
class Main { 
    public static void getFile() throws IOException { 
        throw new IOException("This file does not exist."); 
    } 
    public static void main(String[] args) { 
        try { 
            getFile(); 
        } catch (IOException error) { 
            System.out.println(e.getMessage()); 
        } 
    } 
}

ผลลัพธ์: This file does not exist.

อธิบาย: import java.io คลาส Main มี getFile() โยน IOException พร้อมข้อความ main ใช้ try/catch เรียก getFile() จับ IOException พิมพ์ message

โยน Unchecked Exception (StringIndexOutOfBoundsException)

อยากโยน StringIndexOutOfBoundsException ถ้าเข้าถึง index ไม่มีในสตริง

class Main { 
    public static void outOfBounds() { 
        throw new StringIndexOutOfBoundsException("This index value is invalid."); 
    } 
    public static void main(String[] args) { 
        outOfBounds(); 
    } 
}

ผลลัพธ์: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: This index value is invalid.

สร้าง outOfBounds() โยน exception พร้อมข้อความ main เรียก outOfBounds() -> exception ถูกโยน มักไม่ควรโยน unchecked exceptions (เพราะมาจาก programming errors) แต่แสดงไวยากรณ์ไว้ให้ดู

สรุป

การจัดการ checked exceptions สำคัญต่อโค้ดที่บำรุงรักษาง่าย ใน Java ใช้ throw (โยน exception) และ throws (ประกาศ exception) บทช่วยสอนนี้ครอบคลุมการใช้งานทั้ง 2 keyword พร้อมตัวอย่าง ตอนนี้คุณพร้อม throw และ handle exceptions ใน Java อย่างมืออาชีพแล้ว!