๐ก๏ธ Lesson 6: Error Handling
Why Error Handling Matters
Imagine driving a car without brakes. That's what running code without error handling is like - you're just hoping nothing goes wrong!
โ Without Error Handling
Users lose data, trust, and patience
โ With Error Handling
App stays alive, user stays happy
Today's Project: "Crash-Proof CLI"
We'll build a robust CLI application that:
- ๐ก๏ธ Validates all user inputs
- ๐ง Handles file operations safely
- ๐ Logs errors with stack traces
- ๐ Retries failed operations
- ๐ Provides helpful error messages
Errors vs Exceptions: Know the Difference
๐ Error Classifier Tool
Click on each scenario to see if it's an Error or Exception:
TypeError
Calling a method on null
FormatException
Parsing invalid JSON
Network Failure
Connection timeout
AssertionError
Assert condition fails
๐ด Errors
Programming mistakes that shouldn't be caught
- Indicate bugs in code
- Should be fixed, not handled
- Examples: TypeError, AssertionError
๐ก Exceptions
Recoverable failures that should be handled
- Expected to happen sometimes
- Can be caught and recovered
- Examples: FormatException, IOException
Try/Catch: The Safety Net
๐ฎ Try/Catch Live Simulator
Write code and see how try/catch handles errors in real-time:
๐ Risky Code:
๐ค Output:
๐งฌ Try/Catch Anatomy
try {
Code that might fail
} on SpecificException {
Handle specific errors
} catch (e, stackTrace) {
Catch all exceptions
} finally {
Always runs (cleanup)
Creating Custom Exceptions
๐๏ธ Custom Exception Builder
Design your own exception class:
๐ Generated Exception Class:
class ValidationException implements Exception {
final String message;
final String field;
final dynamic value;
ValidationException({
required this.message,
required this.field,
this.value,
});
@override
String toString() {
return 'ValidationException: $message '
'(field: $field'
'${value != null ? ", value: $value" : ""})';
}
}
Throw & Rethrow: Error Propagation
๐ฏ Throw vs Rethrow Simulator
main() {
processData();
validateInput();
throw Exception();
Click Throw or Rethrow to see the difference!
๐ผ throw
throw Exception('Error occurred');
Creates a new exception with fresh stack trace
๐ rethrow
try {
riskyOperation();
} catch (e) {
log('Error: $e');
rethrow; // Preserves original stack!
}
Preserves the original stack trace for debugging
Real-World Error Handling Patterns
๐งช Error Handling Lab
Test different error handling patterns with realistic scenarios: