How to create a custom exception and handle it in dart
Solution 1
You can look at the Exception part of A Tour of the Dart Language.
The following code works as expected (custom exception has been obtained
is displayed in console) :
class CustomException implements Exception {
String cause;
CustomException(this.cause);
}
void main() {
try {
throwException();
} on CustomException {
print("custom exception has been obtained");
}
}
throwException() {
throw new CustomException('This is my first custom exception');
}
Solution 2
You don't need an Exception class if you don't care about the type of Exception. Simply fire an exception like this:
throw ("This is my first general exception");
Solution 3
Dart code can throw and catch exceptions. In contrast to Java, all of Dart’s exceptions are unchecked exceptions. Methods don’t declare which exceptions they might throw, and you aren’t required to catch any exceptions.
Dart provides Exception
and Error
types, but you’re allowed to throw any non-null object:
throw Exception('Something bad happened.');
throw 'Waaaaaaah!';
Use the try
, on
, and catch
keywords when handling exceptions:
try {
breedMoreLlamas();
} on OutOfLlamasException {
// A specific exception
buyMoreLlamas();
} on Exception catch (e) {
// Anything else that is an exception
print('Unknown exception: $e');
} catch (e) {
// No specified type, handles all
print('Something really unknown: $e');
}
The try
keyword works as it does in most other languages. Use the on
keyword to filter for specific exceptions by type, and the catch
keyword to get a reference to the exception object.
If you can’t completely handle the exception, use the rethrow
keyword to propagate the exception:
try {
breedMoreLlamas();
} catch (e) {
print('I was just trying to breed llamas!.');
rethrow;
}
To execute code whether or not an exception is thrown, use finally
:
try {
breedMoreLlamas();
} catch (e) {
// ... handle exception ...
} finally {
// Always clean up, even if an exception is thrown.
cleanLlamaStalls();
}
Code example
Implement tryFunction()
below. It should execute an untrustworthy method and then do the following:
- If
untrustworthy()
throws anExceptionWithMessage
, calllogger.logException
with the exception type and message (try usingon
andcatch
). - If
untrustworthy()
throws an Exception, calllogger.logException
with the exception type (try usingon
for this one). - If
untrustworthy()
throws any other object, don’t catch the exception. - After everything’s caught and handled, call
logger.doneLogging
(try usingfinally
).
.
typedef VoidFunction = void Function();
class ExceptionWithMessage {
final String message;
const ExceptionWithMessage(this.message);
}
abstract class Logger {
void logException(Type t, [String msg]);
void doneLogging();
}
void tryFunction(VoidFunction untrustworthy, Logger logger) {
try {
untrustworthy();
} on ExceptionWithMessage catch (e) {
logger.logException(e.runtimeType, e.message);
} on Exception {
logger.logException(Exception);
} finally {
logger.doneLogging();
Comments
-
Vickyonit almost 2 years
I have written this code to test how custom exceptions are working in the dart.
I'm not getting the desired output could someone explain to me how to handle it??
void main() { try { throwException(); } on customException { print("custom exception is been obtained"); } } throwException() { throw new customException('This is my first custom exception'); }
-
Vickyonit over 11 yearsi want my exception to be inherited from the Exception class.
-
Alexandre Ardhuin over 11 yearsFYI : Dart programs can throw any non-null object—not just Exception and Error objects—as an exception
-
Kai Sellgren over 11 years@Vickyonit do not inherit from the Exception class, implement it instead. Also, you may want to consider adding a code to the class as well.
-
Oleg Silkin over 5 yearsWouldn't you want the Exception's members to be marked as
final
? -
DarkNeuron almost 5 years@OlegSilkin Yes, always make things final unless mutations are a requirement. Exceptions should never mutate.
-
micimize over 4 years@KaiSellgren should we implement over extend because
Exception
is abstract? What about extending from concrete implementations likeSocketException
? -
netskink over 3 yearsInteresting. new is opitonal in my version of dart, but its helpful to understand its calling the constructor in your example.
-
Ardent Coder over 3 yearsWith reference to "Dart programs can throw any non-null object—not just Exception and Error objects—as an exception." (emphasis mine), I've made an edit to your post because the actual type of the object thrown here is String, which you can verify by the following code snippet:
void main() { try { throw ("Your description is a String");} catch (e) { print(e.runtimeType); } }