'How to create a custom exception and handle it in dart
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');
}
Solution 1:[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:[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:[3]
You can also create an abstract exception.
Inspiration taken from TimeoutException
of async
package (read the code on Dart API and Dart SDK).
abstract class IMoviesRepoException implements Exception {
const IMoviesRepoException([this.message]);
final String? message;
@override
String toString() {
String result = 'IMoviesRepoExceptionl';
if (message is String) return '$result: $message';
return result;
}
}
class TmdbMoviesRepoException extends IMoviesRepoException {
const TmdbMoviesRepoException([String? message]) : super(message);
}
Solution 4:[4]
Try this Simple Custom Exception Example for Beginners
class WithdrawException implements Exception{
String wdExpMsg()=> 'Oops! something went wrong';
}
void main() {
try {
withdrawAmt(400);
}
on WithdrawException{
WithdrawException we=WithdrawException();
print(we.wdExpMsg());
}
finally{
print('Withdraw Amount<500 is not allowed');
}
}
void withdrawAmt(int amt) {
if (amt <= 499) {
throw WithdrawException();
}else{
print('Collect Your Amount=$amt from ATM Machine...');
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Carrie Kendall |
Solution 2 | Ardent Coder |
Solution 3 | |
Solution 4 | Seiji Hirao |