Exception handling is a crucial aspect of any programming language, and Dart is no exception. It allows you to manage errors gracefully and ensure that your program can handle unexpected situations without crashing.

Key Concepts

  1. Exceptions: An exception is an event that disrupts the normal flow of a program's execution.
  2. Throwing Exceptions: You can throw exceptions using the throw keyword.
  3. Catching Exceptions: You can catch exceptions using try, catch, and finally blocks.
  4. Custom Exceptions: You can create your own exceptions by extending the Exception class.

Throwing Exceptions

In Dart, you can throw an exception using the throw keyword. Here's a simple example:

void checkAge(int age) {
  if (age < 18) {
    throw Exception('Age must be 18 or older.');
  }
  print('Age is valid.');
}

void main() {
  checkAge(20); // Age is valid.
  checkAge(15); // Throws an exception
}

In this example, if the age is less than 18, an exception is thrown with a message.

Catching Exceptions

To handle exceptions, you use try, catch, and finally blocks. Here's how you can catch the exception thrown in the previous example:

void checkAge(int age) {
  if (age < 18) {
    throw Exception('Age must be 18 or older.');
  }
  print('Age is valid.');
}

void main() {
  try {
    checkAge(20); // Age is valid.
    checkAge(15); // Throws an exception
  } catch (e) {
    print('Caught an exception: $e');
  } finally {
    print('This block is always executed.');
  }
}

Explanation:

  • try block: Contains the code that might throw an exception.
  • catch block: Handles the exception. The exception object is passed to the catch block.
  • finally block: Contains code that is always executed, regardless of whether an exception was thrown or not.

Custom Exceptions

You can create custom exceptions by extending the Exception class. Here's an example:

class AgeException implements Exception {
  String errorMessage() {
    return 'Age must be 18 or older.';
  }
}

void checkAge(int age) {
  if (age < 18) {
    throw AgeException();
  }
  print('Age is valid.');
}

void main() {
  try {
    checkAge(15); // Throws an exception
  } catch (e) {
    print('Caught an exception: ${e.errorMessage()}');
  }
}

Explanation:

  • Custom Exception Class: AgeException implements the Exception interface and provides a custom error message.
  • Throwing Custom Exception: The checkAge function throws an AgeException if the age is less than 18.
  • Catching Custom Exception: The catch block catches the custom exception and prints the custom error message.

Practical Exercises

Exercise 1: Division by Zero

Write a function that takes two integers and returns their division. If the divisor is zero, throw an exception.

double divide(int a, int b) {
  if (b == 0) {
    throw Exception('Cannot divide by zero.');
  }
  return a / b;
}

void main() {
  try {
    print(divide(10, 2)); // 5.0
    print(divide(10, 0)); // Throws an exception
  } catch (e) {
    print('Caught an exception: $e');
  }
}

Exercise 2: Custom Exception for Negative Numbers

Create a custom exception for handling negative numbers. Write a function that takes an integer and throws the custom exception if the number is negative.

class NegativeNumberException implements Exception {
  String errorMessage() {
    return 'Number cannot be negative.';
  }
}

void checkNumber(int number) {
  if (number < 0) {
    throw NegativeNumberException();
  }
  print('Number is valid.');
}

void main() {
  try {
    checkNumber(10); // Number is valid.
    checkNumber(-5); // Throws an exception
  } catch (e) {
    print('Caught an exception: ${e.errorMessage()}');
  }
}

Common Mistakes and Tips

  • Not Catching Exceptions: Always catch exceptions to prevent your program from crashing unexpectedly.
  • Using Generic Exception: Avoid using the generic Exception class for all errors. Create custom exceptions for specific error types.
  • Ignoring Finally Block: Use the finally block to release resources or perform cleanup tasks, even if an exception occurs.

Conclusion

In this section, you learned about exception handling in Dart, including how to throw and catch exceptions, and how to create custom exceptions. Exception handling is essential for writing robust and error-resistant programs. In the next section, we will explore debugging techniques to help you identify and fix issues in your Dart code.

© Copyright 2024. All rights reserved