មេរៀនទី៤៧: ប្រើ try-catch block

មាន ៥ keywords ប្រើក្នុង Exception handling:
1.    try
2.    catch
3.    finally
4.    throw
5.    throws
try block
បិទកូដ code ដែលអាចបោះចោល exception ក្នុង try block។ វាប្រើជាមួយ method ត្រូវតាម catch ឬ finally block។
Syntax នៃ try with catch block
try{

}catch(Exception_class_Name reference){}
Syntax នៃ try with finally block
try{

}finally{}
catch block
Catch block ត្រូវបានប្រើដើម្បី handle the Exception វាត្រូវបានប្រើក្រោយ try block.
បញ្ហាដោយមិនមាន exception handling
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0;
System.out.println(“rest of the code…”);
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
មានអ្វីកើតឡើងក្រោយកូដ code int a=50/0;
Javaដោះស្រាយដោយ exception handling
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println(“rest of the code…”);
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code…