2月7日 11:29
How to Create Custom Exception Classes in Dart?
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:
- Define a class: Implement the
Exceptioninterface or directly inherit from it. - Add a constructor: Typically, include a constructor that takes an error message.
- Override the
toStringmethod: This allows for more descriptive error messages.
Here is an example demonstrating how to define a custom exception class named CustomException:
dartclass CustomException implements Exception { final String message; CustomException(this.message); String toString() => "CustomException: $message"; }
You can use this custom exception as follows:
dartvoid 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.