មេរៀនទី៥០: finally block

finally block គឺជា block មួយដែលតែងតែ ប្រតិបត្តិ។ វាប្រើដើម្បី កំណត់ ទម្រង់ កិច្ចការមានសំខាន់ ដូចជាបិទ connection, stream ។
Javaហេតុអ្វីបានប្រើ finally block?
•    finally block អាចប្រើដាក់ put “cleanup” code ដូចជាបិទ file, បិទការភ្ជាប់ connection
ករណី 1
កម្មវិធីនៅក្នុងករណីនេះ  exception មិនកើតឡើង
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println(“finally block is always executed”);}
System.out.println(“rest of the code…”);
}
}
Output:5
finally block is always executed
rest of the code…
ករណី 2
កម្មវិធីក្នុងករណីនេះ  exception បានកើតឡើងតែ មិន handled
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println(“finally block is always executed”);}
System.out.println(“rest of the code…”);
}
}
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
ករណី 3
កម្មិធីក្នុងករណីនេះ  exception បានកើតឡើង និង  handled
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println(“finally block is always executed”);}
System.out.println(“rest of the code…”);
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code…