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');
}
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');
}
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");
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);
}
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...');
}
}
Related
in a flutter, I execute multiple functions on initState. Like this:-
#override
void initState() {
super.initState();
function1();
function2();
function3();
function4();
}
in case the function2() has some errors it affects function3(),function4() also. How do we avoid this?
You can call try in each functions to avoid getting stop incase of getting error:
void function1(){
try {
//put you code hear
} catch (e) {
print("e = $e");
}
}
You have to use try & catch but, there is a way to write only at one place !
create a extension on Function to call it & absorb the error if any occures in it.
Here is a example:
import 'dart:developer';
void f1() => print('f1');
void f2() => throw 'STOP';
void f3() => print('f3');
extension FunctionUtils on Function {
void callAndAbsorbError() {
try {
this.call();
} catch (e, st) {
log("Error in $this", error: e, stackTrace: st);
}
}
}
void main(List<String> arguments) {
f1.callAndAbsorbError();
f2.callAndAbsorbError();
f3.callAndAbsorbError();
}
This way you don't need to write try catch in every function you create. AND all your functions will execute for sure.
More about extensions : vandad's blog
I am playing around with dart syntax
And I was trying this code:
void main() {
print("Hello to demo");
try{
throw Test("hello");
}
on Test catch(Test e, StackTrace s){ //error on this line
print("error message is ${(e).message}");
}
}
class Test{
String? message;
Test(this.message);
}
The error message I get is
'catch' must be followed by '(identifier)' or '(identifier, identifier)'.
No types are needed, the first is given by 'on', the second is always 'StackTrace'
I know that dart is strongly typed language but the same time explicitly defining types is optional, but I don't know why am I getting this message here, are there some situations (like the catch here) where even specifying a type is forbidden and not even optional?
p.s.: I am reading the documentation here
Simply catch is a keyword, not a function, and it is designed in a way that you can't set parameter types. You have to use it as documented here, like:
try {
// ยทยทยท
} on Exception catch (e) {
print('Exception details:\n $e');
} catch (e, s) {
print('Exception details:\n $e');
print('Stack trace:\n $s');
}
Your code works this way:
void main() {
print("Hello to demo");
try {
throw Test("hello");
}
on Test catch(e, s){
print("error message is ${(e).message}");
print("stacktrace is ${(s)}");
}
}
class Test {
String? message;
Test(this.message);
}
A data class in Dart:
import 'package:validate/validate.dart';
class AuthUser {
final String email, token, username, bio, image;
AuthUser(this.email, this.token, this.username, this.bio, this.image) {
Validate.isEmail(this.email);
}
#override
String toString() {
return 'AuthUser{email: $email, token: $token, username: $username, bio: $bio, image: $image}';
}
}
where Validate.isEmail will throws an Error when failed to match:
static void matchesPattern(String input, RegExp pattern,[String message = DEFAULT_MATCHES_PATTERN_EX]) {
if (pattern.hasMatch(input) == false) {
throw new ArgumentError(message);
}
}
static void isEmail(String input,[String message = DEFAULT_MATCHES_PATTERN_EX]) {
matchesPattern(input,new RegExp(PATTERN_EMAIL),message);
}
Now I want to use an elegant way to new this class.
When using Scala, I can use Try(new AuthUser(...)) and patten-matching it.
And in Dart, first I tried RxDart,
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
Observable.just(AuthUser("email", "token", "username", "bio", "img"))
.doOnError((e, s) => print("oh no"))
.listen((e) => print(e.toString()));
});
}
Not work, the test failed for the error(which means RxDart doesn't catch errors at all!!!)
And I want to try Future, failed also.
And I want to use dartz, but I am worried because there is just one maintainer...
Any advice?
If you are OK with using Future what's wrong with this advice: Using Future.sync() to wrap your code? The code will look like this:
void main() {
var f = Future.sync(() {AuthUser("email", "token", "username", "bio", "img"); });
f.then((v) => print("Value: " + v.toString())).catchError((e) => print("Failure: " +e.toString()));
}
The main trick is that Future.sync effectively enables lazy evaluation of the parameter but you have to pass your parameter wrapped in a function. This is actually the same trick Scala compiler does for Try (i.e. for call-by-name parameters) but takes adding a few brackets around.
If you only want the basic functionality of returning either type based on whether an exception occurred or not then you can easily create a utility class such as below.
Otherwise I recommend #SergGr's answer about using Future.sync since it gives you more monadic like pipeline.
void main() {
Try<Error, void> result = Try.it(() => Validate.isEmail("test-example.com"));
if (result is Success) {
print("Good");
} else if (result is Failure) {
print("Error: " + result.exception().toString());
}
}
typedef TryExec<V> = V Function();
abstract class Try<E extends Error, V> {
static Try<E, V> it<E extends Error, V>(TryExec<V> fn) {
try {
return Try.success(fn());
} catch (e) {
return Try.failure(e);
}
}
static Try<E, V> failure<E extends Error, V>(Error e) {
return new Failure(e);
}
static Try<E, V> success<E extends Error, V>(V v) {
return new Success(v);
}
}
class Failure<E extends Error, V> extends Try<E, V> {
final E _e;
Failure(this._e);
E exception() => _e;
}
class Success<E extends Error, V> extends Try<E, V> {
final V _v;
Success(this._v);
V value() => _v;
}
I have a class with a method that throws some exceptions and catches them inside itself, but when i call it in my Main class they seem to not being catched.
An example about my problem:
public class Test {
public static void method (int number) throws InvalidNumberException {
try {
if (number == 5) {
throw new InvalidNumberException("Invalid number");
}
} catch (InvalidNumberException inv) {
System.out.println(inv);
}
}
}
public class InvalidNumberException extends Exception {
public InvalidNumberException (String s) {
super(s);
}
}
public class Main {
public static void main(String args[]) {
Test.method(5);
}
}
When i try to compilate the last one i get this error:
Main.java:3: error: unreported exception InvalidNumberException; must be caught or declared to be thrown
Test.method(5);
Is there a way to fix it without catching the exception in the Main class?
Because you're catching the InvalidNumberException inside of method, there's no need for a throws clause, however, the existence of it mandates that calls to it must handle the exception. Thus, the compiler is expecting you to handle the exception in main.
To solve this, simply remove the throws clause modifying method, since you're already handling the exception inside.
I have this method and the first log prints, the others don't
What am I doing wrong?
That is this :Log.d("insideGetFriends","in"); Gets printed and I looked in my log,
Log.d("facebookError",Integer.toString(graphUsers.size())); and the remaining lines do not get executed.
public ArrayList<ParseUser> getFriends(Session session)
{
Log.d("insideGetFriends","in");
final ArrayList<ParseUser> users=new ArrayList<>();
Request.newMyFriendsRequest(session,new Request.GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> graphUsers, Response response) {
Log.d("facebookError",Integer.toString(graphUsers.size()));
for(GraphUser user:graphUsers)
{
String facebookId=user.getId();
Log.d("facebookFriend",facebookId);
ParseQuery<ParseUser> query=ParseUser.getQuery();
query.whereEqualTo("facebookID",facebookId);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> parseUsers, ParseException e) {
users.add(parseUsers.get(0));
}
});
}
}
});
return users;
}
It looks like you are not starting/executing the request.
You need to store the result of Request.newMyFriendsRequest(...) in a variable and then call .executeAsync() on it.
This is explained here: https://developers.facebook.com/docs/android/graph#userdata