Dart Exception Handling


Exception Handling in Dart (OOP)

In Dart, exception handling is used to manage errors and other unexpected situations that can occur during the execution of a program. Exception handling allows developers to write code that can gracefully handle errors rather than causing the entire program to crash.

Dart provides the try, catch, and finally blocks for handling exceptions:

  • try: Wraps the code that might throw an exception.
  • catch: Catches the exception and allows you to handle it.
  • on: Specifies the type of exception you want to catch.
  • finally: Executes code after try and catch blocks, regardless of whether an exception was thrown.

Example of Exception Handling in Dart (OOP)

Suppose we are building a BankAccount class where each account has an accountHolder and a balance. We will implement a withdraw method that throws an exception if an attempt is made to withdraw an amount greater than the balance.

Code Example:

// Custom exception class for insufficient funds class InsufficientFundsException implements Exception { String errorMessage() => 'Insufficient funds in the account!'; } // BankAccount class class BankAccount { String accountHolder; double balance; // Constructor BankAccount(this.accountHolder, this.balance); // Method to withdraw amount from account void withdraw(double amount) { if (amount > balance) { throw InsufficientFundsException(); } balance -= amount; print("Withdrawal successful! New balance: \$${balance.toStringAsFixed(2)}"); } } void main() { // Create a new BankAccount instance var account = BankAccount("Alice", 1000.0); // Attempt to withdraw an amount within the balance try { print("Attempting to withdraw \$300.0..."); account.withdraw(300.0); // Successful withdrawal } catch (e) { print(e); } // Attempt to withdraw an amount exceeding the balance try { print("\nAttempting to withdraw \$800.0..."); account.withdraw(800.0); // This will throw an exception } on InsufficientFundsException catch (e) { print(e.errorMessage()); } finally { print("Transaction completed."); } }

Explanation:

  1. Custom Exception (InsufficientFundsException):

    • A custom exception class is created by implementing the Exception interface.
    • It includes a method errorMessage() that returns an error message.
  2. BankAccount Class:

    • BankAccount has two properties, accountHolder and balance.
    • The withdraw method checks if the withdrawal amount is greater than the balance.
      • If it is, it throws an InsufficientFundsException.
      • If not, it subtracts the amount from balance and prints the updated balance.
  3. Exception Handling in main():

    • First try-catch Block:
      • The program attempts to withdraw $300, which is within the balance, so it is successful.
    • Second try-on-catch-finally Block:
      • The program attempts to withdraw $800, which exceeds the balance, causing an InsufficientFundsException.
      • The on InsufficientFundsException block catches the exception, and the catch block prints a custom error message.
      • The finally block executes regardless of whether the exception was thrown, indicating that the transaction is completed.

Output:

Attempting to withdraw $300.0... Withdrawal successful! New balance: $700.00 Attempting to withdraw $800.0... Insufficient funds in the account! Transaction completed.

Benefits of Exception Handling in Dart OOP

  1. Increased Reliability: Proper exception handling ensures the program can handle unexpected errors gracefully, preventing crashes.
  2. Improved Code Clarity: By handling exceptions in specific try, catch, on, and finally blocks, the code is more structured and readable.
  3. Custom Error Messages: Custom exception classes allow for more informative error messages, improving the debugging process.
  4. Better User Experience: Instead of terminating the program abruptly, exceptions can be handled to provide meaningful feedback, making the user experience smoother.

Summary

Exception handling in Dart, especially with custom exception classes in OOP, provides a robust mechanism to handle errors without disrupting the flow of a program. In the BankAccount example, we demonstrated how to throw and catch a custom exception for insufficient funds, enhancing error feedback and ensuring that the program continues executing smoothly.