មេរៀនទី៥១: throw keyword
throw keyword ត្រូវបានប្រើដើម្បី ធ្វើអោយជាក់លាក់ក្នុង exception។ យើងអាច ប្រើ
checked ឬ uncheked exception។
ឧទាហរណ៍នស throw keyword
ក្នុងឧទាហរណ៍នេះ យើងបានបង្កើត validate method ដែលយកតម្លៃជា integer value ដូចជាប៉ារ៉ាម្រែត parameter។ ប្រសិនបើ អាយុតិចជា 18, យើងប្រើ ArithmeticException print សារ message ចេញ។
public class TestThrow1{
static void validate(int age){
if(age<18 br=""> throw new ArithmeticException(“not valid”);
else
System.out.println(“welcome to vote”);
}18>
public static void main(String args[]){
validate(13);
System.out.println(“rest of the code…”);
}
}
Output:Exception in thread main java.lang.ArithmeticException:not valid
checked ឬ uncheked exception។
ឧទាហរណ៍នស throw keyword
ក្នុងឧទាហរណ៍នេះ យើងបានបង្កើត validate method ដែលយកតម្លៃជា integer value ដូចជាប៉ារ៉ាម្រែត parameter។ ប្រសិនបើ អាយុតិចជា 18, យើងប្រើ ArithmeticException print សារ message ចេញ។
public class TestThrow1{
static void validate(int age){
if(age<18 br=""> throw new ArithmeticException(“not valid”);
else
System.out.println(“welcome to vote”);
}18>
public static void main(String args[]){
validate(13);
System.out.println(“rest of the code…”);
}
}
Output:Exception in thread main java.lang.ArithmeticException:not valid
Post a Comment