How to Handle Exceptions in Dart

Exception handling is an essential part of programming that allows you to manage errors gracefully. In Dart, exceptions can be handled using try, catch, finally, and throw statements. This enables you to write robust applications that can respond to unexpected situations without crashing.

1. Using try and catch

The try block contains code that may throw an exception, while the catch block contains code that handles the exception. You can catch specific exceptions or use a general catch block.

Example of try and catch

void main() {
try {
int result = 10 ~/ 0; // This will throw an exception (division by zero)
print('Result: $result');
} catch (e) {
print('Caught an exception: $e'); // Handling the exception
}
}

2. Catching Specific Exceptions

You can catch specific types of exceptions by specifying the exception type in the catch block. This allows for more granular error handling.

Example of Catching Specific Exceptions

void main() {
try {
int result = int.parse('not a number'); // This will throw a FormatException
print('Result: $result');
} on FormatException catch (e) {
print('Caught a FormatException: $e'); // Handling specific exception
} catch (e) {
print('Caught an exception: $e'); // Handling any other exception
}
}

3. Using finally

The finally block is optional and will execute after the try and catch blocks, regardless of whether an exception was thrown or not. This is useful for cleanup operations, such as closing files or releasing resources.

Example of finally

void main() {
try {
int result = 10 ~/ 0; // This will throw an exception
print('Result: $result');
} catch (e) {
print('Caught an exception: $e');
} finally {
print('This will always execute.'); // Cleanup code
}
}

4. Throwing Exceptions

You can throw exceptions manually using the throw statement. This is useful for enforcing certain conditions in your code.

Example of Throwing Exceptions

void checkAge(int age) {
if (age < 18) {
throw Exception('Age must be at least 18.'); // Throwing an exception
}
print('Access granted.');
}

void main() {
try {
checkAge(16); // This will throw an exception
} catch (e) {
print('Caught an exception: $e'); // Handling the thrown exception
}
}

5. Custom Exceptions

You can also create your own custom exception classes by extending the Exception class. This allows you to define specific error types for your application.

Example of Custom Exceptions

class AgeException implements Exception {
String cause;
AgeException(this.cause);
}

void checkAge(int age) {
if (age < 18) {
throw AgeException('Age must be at least 18.'); // Throwing a custom exception
}
print('Access granted.');
}

void main() {
try {
checkAge(16); // This will throw a custom exception
} catch (e) {
print('Caught an exception: $e'); // Handling the custom exception
}
}

Conclusion

Handling exceptions in Dart is straightforward and allows you to manage errors effectively. By using try, catch, finally, and throw, you can create robust applications that can gracefully handle unexpected situations. Understanding how to work with exceptions is crucial for writing reliable and maintainable Dart code.