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

สามารถเขียนคำสั่งระหว่าง try, catch และ finally blocks ใน Java ได้หรือไม่?

ไม่สามารถ เราไม่สามารถเขียนคำสั่งใดๆ ระหว่าง try, catch และ finally blocks และบล็อกเหล่านี้ เป็นหน่วยเดียว (form one unit) ฟังก์ชันของ try keyword คือระบุ exception object และจับ exception object นั้น แล้วส่งการควบคุมพร้อมกับ exception object ที่ระบุไปยัง catch block โดยระงับการทำงานของ try block ฟังก์ชันของ catch block คือรับ exception class object ที่ส่งมาจาก try และ จับ (catch) exception class object นั้น แล้วกำหนดให้ reference ของ exception class ที่ตรงกันใน catch block Finally blocks เป็นบล็อกที่จะทำงาน บังคับ (compulsorily) ไม่ว่าจะมี exception เกิดขึ้นหรือไม่

เราสามารถเขียนได้แค่ try with catch block, try with multiple catch blocks, try with finally block และ try with catch and finally blocks และไม่สามารถเขียนโค้ดหรือคำสั่งระหว่างการรวมกันเหล่านี้ได้ หากลองวางคำสั่งระหว่างบล็อกเหล่านี้ จะเกิด compile-time error

Syntax

try {
    // Statements to be monitored for exceptions
} // We can't keep any statements here
catch(Exception ex){
    // Catching the exceptions here
} // We can't keep any statements here
finally{
    // finally block is optional and can only exist if try or try-catch block is there.
    // This block is always executed whether exception is occurred in the try block or not
    // and occurred exception is caught in the catch block or not.
    // finally block is not executed only for System.exit() and if any Error occurred.
}

ตัวอย่าง

public class ExceptionHandlingTest {
    public static void main(String[] args) {
        System.out.println("We can keep any number of statements here");
        try {
            int i = 10/0; // This statement throws ArithmeticException
            System.out.println("This statement will not be executed");
        } // We can't keep statements here
        catch(ArithmeticException ex){
            System.out.println("This block is executed immediately after an exception is thrown");
        } // We can't keep statements here
        finally {
            System.out.println("This block is always executed");
        }
        System.out.println("We can keep any number of statements here");
    }
}

ผลลัพธ์

We can keep any number of statements here
This block is executed immediately after an exception is thrown
This block is always executed
We can keep any number of statements here