Using finally

ธนกร ภควณิช 650710984

finally คืออะไร

ในการเขียนโปรแกรม ข้อยกเว้นอาจทำให้มีปัญหาหรือเกิดข้อผิดพลาดได้ ทำให้การทำงานหรือเมธอดอาจหยุดการทำงานลงได้ เพื่อแก้ปัญหาเหล่านี้จึงคีเวิร์ดตัวนึงที่มีชื่อว่า Finally Finally จะเริ่มการทำงานหลังจาก Try และ Catch จบการทำงานไม่ว่า Try จะถูกหยุดการทำงานด้วยข้อยกเว้น

C#

จุดสำคัญของ finally ใน C# คือ 1.บล็อคของ finally ไม่ควรมีหลายบล็อคในโปรแกรมเดียวกันได้ 2.finally ไม่มีควรใช้ return, break หรือ continue 3.finally สามารถใช้คู่กับ try โดยที่ไม่ต้องมี catch ก็ได้ยังไง finally ก็ยังคงทำงานต่อจาก try

C# Ex1

เคสที่ 1 โค๊ดจะรันตามปกติแต่จะไปเจอปัญหาตรงเอา 0 มาหารเลยทำให้บล็อคของ catch แสดงประโยคออกมาว่า Not possible to divide by zero!

using System; 
  
public class GFG { 
  
    // Main Method 
    static public void Main() 
    { 
  
        // variables 
        int number = 4; 
        int divisor = 0; 
  
        // try block 
        // This block raise exception 
        try { 
  
            int output = number / divisor; 
        } 
  
        // catch block 
        // This block handle exception 
        catch (DivideByZeroException) { 
  
            Console.WriteLine("Not possible to divide by zero!"); 
        } 
  
        // finally block 
        // This block release the  
        // resources of the system 
        // and this block always executes 
        finally { 
  
            Console.WriteLine("Finally Block!"); 
        } 
    } 
} 

Output

Not possible to divide by zero!
Finally Block!

C# Ex2

เคสที่ 2 จะมีปัญหาหรือerror ตรงที่ 0 ไม่สามารถหารกับ 4 ได้ แต่ยังไงก็ตาม finally ก็ยังคงทำงานต่อ

using System; 
   
public class GFG {      
    static public void Main () { 
    int number = 4; 
    int divisor = 0; 
    int output;     
       
    try
    { 
         output = number/divisor;       
    } 
       
    finally
    { 
        Console.WriteLine("Finally Block!"); 
    } 
    } 
} 

Output

Finally Block!

Java

Java Ex1

เคสที่ 1 โค๊ดจะรันอย่างปกติดีในส่วนของ catch หรือ (except) จะไม่ทำงานเพราะ 34/2 ได้โดยไม่มีปัญหาอะไร

import java.io.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
        try { 
            System.out.println("inside try block");         
            System.out.println(34 / 2); 
        } 
        
        catch (ArithmeticException e) { 
            
            System.out.println("Arithmetic Exception"); 
            
        } 
        finally {          
            System.out.println( 
                "finally : i execute always."); 
            
        } 
    } 
}

Output

inside try block
17
finally : i execute always.

Java Ex2

เคสที่ 2 โค๊ดจะรันไปถึง 34/0 แต่ก็พบปัญหาเพราะ 0 ไม่สามารถหารได้ จึงทำให้ catch รันและแสดงข้อความว่า catch : exception handled.

import java.io.*; 
  
class GFG { 
    
    public static void main(String[] args) 
    { 
        try { 
            System.out.println("inside try block"); 
  
            // Throw an Arithmetic exception 
            System.out.println(34 / 0); 
        } 
  
        // catch an Arithmetic exception 
        catch (ArithmeticException e) { 
  
            System.out.println( 
                "catch : exception handled."); 
        } 
  
        // Always execute 
        finally {   
            
          System.out.println("finally : i execute always."); 
        } 
    } 
}

Output

inside try block
catch : exception handled.
finally : i execute always.

Python

จุดสำคัญของ finally ใน Python คือ 1.ใน Python หากเราจะใช้ catch เราจะต้องเปลี่ยนเป็น except แทน 2.ส่วนต่างๆก็จะคล้ายๆภาษาอื่นๆ

Python Ex1

เคสที่ 1 โค๊ดรันแต่เจอปัญหาคือ 0 ไม่สามารถหารได้จึงทำให้ except ทำงาน และแสดงข้อความว่า Can't divide by zero แล้วหลังจากนั้น finally ก็รันตามปกติ

try:
    k = 5//0 # raises divide by zero exception.
    print(k)
  
except ZeroDivisionError:   
    print("Can't divide by zero")
     
finally:
    print('This is always executed') 

Output

Can't divide by zero
This is always executed

Python Ex2

เคสที่ 2 ในส่วนนี้จะรันได้ตามปกติและไม่พบปัญหา try จะแสดงค่า k ออกมา แล้วก็ข้ามไป finally ทำงานตามปกติ

try:
    k = 5//1 # No exception raised
    print(k)
   
except ZeroDivisionError:   
    print("Can't divide by zero")
     
finally:
    print('This is always executed') 

Output

5
This is always executed

Python Ex3

เคสที่ 3 ในส่วนนี้ 0 ไม่สามารถหาร 5 ได้ และโค๊ดนี้ไม่มี except แต่ก็ไม่เป็นอะไร finally ก็ยังสามารถรันได้ต่อ

try:
    k = 5//0 # exception raised
    print(k)
     
finally:
    print('This is always executed') 

Output

This is always executed

สรุป

ทั้ง 3 ภาษา C# / Java / Python การใช้ finally มีจุดประสงค์เดียวกับหมดคือเพื่อให้แน่ใจว่าโค๊ดในบล็อคนี้รันเสมอ หลังจาก Try หรือ Catch จบการทำงาน แต่ใน Python จะต้องใช้ except แทน catch

Slide and Video presentation

Reference

Last updated