상세 컨텐츠

본문 제목

Dart - Exception Handling

Dart

by techbard 2024. 1. 5. 20:40

본문

반응형
// Why Is Exception Handling Needed?
// Exceptions provide the means to separate the details of
// what to do when something out of the ordinary happens
// from the main logic of a program.
// Therefore, exceptions must be handled to prevent
// the application from unexpected termination.
// Here are some reasons why exception handling is necessary:

// To avoid abnormal termination of the program.
// To avoid an exception caused by logical error.
// To avoid the program from falling apart when an exception occurs.
// To reduce the vulnerability of the program.
// To maintain a good user experience.
//  To try providing aid and some debugging in case of an exception.

// How to Create & Handle Exception

class MarkException implements Exception {
  String errMsg() {
    return "Makrs cannot be negative value.";
  }
}

void checkMark(int mark) {
  if (mark < 0) {
    throw MarkException().errMsg();
  }
}

void main(List<String> args) {
  try {
    checkMark(-1);
  } catch (e) {
    print(e);
  }
}

// 결과
Makrs cannot be negative value.

 

void main(List<String> args) {
  String msg = "Hello";
  try {
    var s = getCharAt(msg, 10);
    print(s);
  } catch (e) {
    print(e);
  }
}

String getCharAt(String s, int index) {
  if (index.isNegative || index > s.length) {
    throw Exception("Index is out of range.");
  }
  return s[index];
}

// 결과
Exception: Index is out of range.

 

void main(List<String> args) {
  try {
    print(EmailAddress(email: 'me@example.com'));
    print(EmailAddress(email: 'example.com'));
    print(EmailAddress(email: ''));
  } on FormatException catch (e) {
    print(e);
  }
}

class EmailAddress {
  final String email;

  EmailAddress({required this.email}) {
    if (email.isEmpty) {
      throw FormatException('email cannot be empty');
    }

    if (!email.contains('@')) {
      throw FormatException("$email doesn't contain the @ symbol");
    }
  }

  @override
  String toString() => email;
}

// 결과
me@example.com
FormatException: example.com doesn't contain the @ symbol

 

void main(List<String> args) {
  final invalidAge = PositiveInt(value: -1);
  print(invalidAge);
}

class PositiveInt {
  final int value;

  const PositiveInt({required this.value})
      : assert(value >= 0, 'Value cannot be negative.');
}


/*
Error handling & Exceptions

Different kinds of errors. Some examples:

- Read or write files => I/O errors
- Network request => networking errors
- Programmer errors

Errors vs Exceptions

- Assertions
- throw exceptions
- try, catch, finally, rethrow

GOAL: Learn how to handle errors gracefully

Errors vs Exceptions

what is the different?

Error
-> Programmer mistake (we did something wrong.)
-> Calling a function with invalid arguments, index out of bounds etc.
-> Program should terminate immediately (not safe to recover)

Exception
-> Failure condition: something unexpected happened.
-> Unexpected: out of our control.
-> Handle it (e.g. show message to user) and recover.

Note about Flutter Apps
- Assertions are enabled in Debug mode
- Assertions are disabled in Release mode
- Assertions are only a safety net to catch runtimr errors eary
- Exceptions are triggered in debug and release mode

*/

// 결과
me@example.com
FormatException: example.com doesn't contain the @ symbol

 

// ignore_for_file: public_member_api_docs, sort_constructors_first
void main(List<String> args) {
  var list = [1, 2, 3, 4, 5];

  try {
    print(list[10]);
  } catch (e, f) {
    print(e); // error message
    print(f); // stack trace
  } finally {
    print('done'); // my application did not stop.
  }

  print('-----' * 5);

  // var account = BankAccount.newClient(-100);

  try {
    var account = BankAccount.newClient(-100);
    print(account.balance);
  } catch (e) {
    print(e);
  } finally {
    print('done'); // my application did not stop.
  }

  print('=====' * 5);

  try {
    var account = BankAccount.newClient(-100);
    print(account.balance);
  } on ZeroBalanceException catch (e) {
    print(e);
  } finally {
    print('done'); // my application did not stop.
  }
}

class BankAccount {
  double balance;

  // BankAccount({required this.balance});

  BankAccount.newClient(double balance) : this.balance = balance {
    if (balance < 0) {
      // throw Exception('The balance cannot be less than 0');
      throw ZeroBalanceException(balance);
    }
  }
}

// more specific custom exception
class ZeroBalanceException implements Exception {
  final double balance;
  const ZeroBalanceException(this.balance);

  @override
  String toString() {
    return 'ZeroBalanceException: Balance: $balance You balance cannot be less than 0';
  }
}

// 결과
RangeError (index): Invalid value: Not in inclusive range 0..4: 10
#0      List.[] (dart:core-patch/growable_array.dart:264:36)
#1      main (file:///C:/Users/SKTelecom/Documents/Dart_code/dart_basics/bin/d56.dart:6:15)
#2      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:295:33)
#3      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

done
-------------------------
ZeroBalanceException: Balance: -100.0 You balance cannot be less than 0
done
=========================
ZeroBalanceException: Balance: -100.0 You balance cannot be less than 0
done
반응형

관련글 더보기

댓글 영역