乐闻世界logo
搜索文章和话题

How to Create Custom Exception Classes in Dart?

2月7日 11:29

In Dart, you can create custom exception classes by implementing or extending the Exception or Error classes. Generally, for exceptions that developers expect to handle through programmatic control logic, use Exception; for internal program errors, use Error.

Here are the steps to create a custom exception class:

  1. Define a class: Implement the Exception interface or directly inherit from it.
  2. Add a constructor: Typically, include a constructor that takes an error message.
  3. Override the toString method: This allows for more descriptive error messages.

Here is an example demonstrating how to define a custom exception class named CustomException:

dart
class CustomException implements Exception { final String message; CustomException(this.message); String toString() => "CustomException: $message"; }

You can use this custom exception as follows:

dart
void someFunction() { throw CustomException('This is a custom error'); } void main() { try { someFunction(); } catch (e) { print(e); } }

When someFunction is called, it throws CustomException, which is then caught and printed in the main function.

标签:Dart