Exception Handling
Exception Handling (ការគ្រប់គ្រងកំហុស) ក្នុង Java
⚠️ Exception គឺជាអ្វី?
Exception គឺព្រឹត្តិការណ៍ដែលមិនរំពឹងទុកដែលកើតឡើងកំឡុងពេលដំណើរការកម្មវិធី ហើយរំខានដល់ normal flow នៃកម្មវិធី។
ឧទាហរណ៍:
- ចែកដោយ 0 → ArithmeticException
- Access array out of bounds → ArrayIndexOutOfBoundsException
- File មិនឃើញ → FileNotFoundException
- Null reference → NullPointerException
- Format ខុស → NumberFormatException
📖 Error vs Exception
លក្ខណៈ | Error | Exception |
---|---|---|
អ្វីជា | បញ្ហា serious (System level) | បញ្ហា recoverable (Application level) |
ឧទាហរណ៍ | OutOfMemoryError, StackOverflowError | IOException, NullPointerException |
ការពារបាន | ❌ មិនអាចគ្រប់គ្រង | ✅ អាចគ្រប់គ្រងបាន |
រំពឹងទុក | Unexpected, fatal | Expected, can handle |
💡 ហេតុអ្វីត្រូវគ្រប់គ្រង Exceptions?
- Prevent Crash: កម្មវិធីមិនឈប់ភ្លាមៗ
- User Experience: បង្ហាញសារកំហុសច្បាស់
- Debugging: ងាយស្វែងរកបញ្ហា
- Resource Management: បិទ files, connections ត្រឹមត្រូវ
- Maintain Normal Flow: បន្តដំណើរការ
- Security: មិនបង្ហាញព័ត៌មានសំខាន់
🎯 Exception Hierarchy
Throwable
├── Error (System problems - cannot handle)
│ ├── OutOfMemoryError
│ ├── StackOverflowError
│ └── VirtualMachineError
│
└── Exception (Can handle)
├── RuntimeException (Unchecked)
│ ├── ArithmeticException
│ ├── NullPointerException
│ ├── ArrayIndexOutOfBoundsException
│ ├── NumberFormatException
│ └── IllegalArgumentException
│
└── Other Exceptions (Checked)
├── IOException
├── FileNotFoundException
├── SQLException
└── ClassNotFoundException
📊 Checked vs Unchecked Exceptions
លក្ខណៈ | Checked Exception | Unchecked Exception |
---|---|---|
Parent Class | Exception (not RuntimeException) | RuntimeException |
Compile Time | Compiler ត្រួតពិនិត្យ | Compiler មិនត្រួតពិនិត្យ |
Must Handle? | ✅ ត្រូវតែ handle | ❌ Optional |
When? | Compile time | Runtime |
ឧទាហរណ៍ | IOException, SQLException | NullPointerException, ArithmeticException |
Cause | External factors (files, network) | Programming errors |
🛠️ Exception Handling - try-catch
✅ Basic Syntax
try {
// Code ដែលអាចកើត exception
} catch (ExceptionType e) {
// Code ដើម្បីគ្រប់គ្រង exception
}
🔑 ឧទាហរណ៍មូលដ្ឋាន
// ❌ WITHOUT EXCEPTION HANDLING
int result = 10 / 0; // Program crashes!
// ✅ WITH EXCEPTION HANDLING
try {
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
System.out.println("Program continues...");
📚 Multiple catch Blocks
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[10]); // ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds!");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} catch (Exception e) {
System.out.println("Some error occurred: " + e.getMessage());
}
⚠️ Important Rule:
Catch specific exceptions មុន general exceptions!
// ❌ WRONG
try {
// code
} catch (Exception e) { // General first
// ...
} catch (ArithmeticException e) { // Specific later - ERROR!
// ...
}
// ✅ CORRECT
try {
// code
} catch (ArithmeticException e) { // Specific first
// ...
} catch (Exception e) { // General later
// ...
}
Java Code
Click "Run" to execute the Java code
🔒 finally Block
📖 finally គឺជាអ្វី?
finally block គឺ code ដែលដំណើរការជានិច្ចមិនថាមាន exception ឬអត់។
✅ Syntax
try {
// Code that may throw exception
} catch (ExceptionType e) {
// Handle exception
} finally {
// Always executes (cleanup code)
}
🎯 ប្រើប្រាស់ finally សម្រាប់:
- បិទ files
- បិទ database connections
- Release resources
- Cleanup operations
💡 ឧទាហរណ៍:
try {
System.out.println("Opening file...");
int result = 10 / 0; // Exception
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Closing file..."); // Always executes
}
📊 Execution Flow
Scenario | try | catch | finally |
---|---|---|---|
មិនមាន exception | ✅ | ❌ | ✅ |
មាន exception & caught | ✅ (partial) | ✅ | ✅ |
មាន exception & not caught | ✅ (partial) | ❌ | ✅ |
🚀 throw and throws Keywords
🔹 throw - Throwing Exceptions
ប្រើដើម្បីបង្កើត និង throw exception manually។
public void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18+");
}
System.out.println("Access granted");
}
// Usage
checkAge(15); // Throws exception
🔹 throws - Declaring Exceptions
ប្រើដើម្បីប្រកាសថា method អាចបង្ក exception។
public void readFile(String path) throws IOException {
// Code that may throw IOException
FileReader fr = new FileReader(path);
// ...
}
📊 throw vs throws
លក្ខណៈ | throw | throws |
---|---|---|
ទីតាំង | ខាងក្នុង method body | ក្នុង method signature |
បម្រើការ | បង្ក exception | ប្រកាស exception |
Syntax | throw new Exception(); | void method() throws Exception |
ចំនួន | Throw one exception | Declare multiple exceptions |
Java Code
Click "Run" to execute the Java code
🎨 Custom Exceptions
📖 ហេតុអ្វីបង្កើត Custom Exceptions?
- Create meaningful exceptions សម្រាប់ application
- Better error messages
- Specific business logic validation
✅ របៀបបង្កើត
// Extend Exception (checked) or RuntimeException (unchecked)
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String message) {
super(message);
}
}
💡 ឧទាហរណ៍ពេញលេញ
class InvalidEmailException extends Exception {
public InvalidEmailException(String email) {
super("Invalid email format: " + email);
}
}
class User {
private String email;
public void setEmail(String email) throws InvalidEmailException {
if (!email.contains("@")) {
throw new InvalidEmailException(email);
}
this.email = email;
}
}
// Usage
try {
User user = new User();
user.setEmail("invalid-email"); // Throws InvalidEmailException
} catch (InvalidEmailException e) {
System.out.println("Error: " + e.getMessage());
}
✅ Best Practices
- Catch specific exceptions: មិនត្រូវ catch Exception រាល់គ្រប់
- Don't swallow exceptions: Log ឬ handle ត្រឹមត្រូវ
- Finally for cleanup: Close resources នៅ finally
- Meaningful messages: Exception message ត្រូវច្បាស់
- Don't use for control flow: Exceptions សម្រាប់ errors only
- Document exceptions: Use @throws in JavaDoc
⚠️ Common Mistakes
កំហុស | ហេតុផល | ដំណោះស្រាយ |
---|---|---|
Empty catch block | លាក់កំហុសដោយមិនដឹង | Log exception ឬ rethrow |
catch (Exception e) | Too broad, catch everything | Catch specific exceptions |
មិនបិទ resources | Memory leaks | Use finally ឬ try-with-resources |
Exception for control | Performance issues | Use if-else conditions |
Java Code
Click "Run" to execute the Java code