Why do we put "e" in our catch argument, in Flutter/Dart? - flutter

For instance:
try{
Parser p = Parser();
Expression exp = p.parse(expression);
ContextModel cm = ContextModel();
evaluated = exp.evaluate(EvaluationType.REAL, cm);
result = '$evaluated';
}
catch(e)
{
result = "no";
}
I see a lot of flutter related youtube tutorials simply putting "e" as their argument in the catch. Why do we do this? Does e simply mean any type of error?

No there is no special meaning, e is used as a placeholder. You can actually put any letter or allowed symbol like (_), and it will still represent the exception type incoming when error is thrown.

The parameter of catch is the exception object that is being thrown.

It's just the name of exeption, you can call it "exeption" or "e" . In most cases you`re going to see this written as "e" - short for exeption or error.

Related

Pre-compile textual replacement macro with arguments

I am trying to create some kind of a dut_error wrapper. Something that will take some arguments and construct them in a specific way to a dut_error.
I can't use a method to replace the calls to dut_error because to my understanding after check that ... then ... else can only come a dut_error (or dut_errorf). And indeed if I try to do something like:
my_dut_error(arg1: string, arg2: string) is {
dut_error("first argument is ", arg, " and second argument is ", arg2);
};
check that FALSE else my_dut_error("check1", "check2");
I get an error:
*** Error: Unrecognized exp
[Unrecognized expression 'FALSE else my_dut_error("check1", "check2")']
at line x in main.e
check that FALSE else my_dut_error("check1", "check2");
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
So I thought about defining a macro to simply do a textual replace from my wrapper to an actual dut_error:
define <my_dut_error'exp> "my_dut_error(<arg1'name>, <arg2'name>)" as {
dut_error("first argument is ", <arg1'name>, " and second argument is ", <arg2'name>)
};
But got the same error.
Then I read about the preprocessor directive #define so tried:
#define my_dut_error(arg1, arg2) dut_error("first argument is ", arg, " and second argument is ", arg2)
But that just gave a syntax error.
How can I define a pre-compiled textual replacement macro that takes arguments, similar to C?
The reason I want to do that is to achieve some sort of an "interface" to the dut_error so all errors have a consistent structure. This way, different people writing different errors will only pass the arguments necessary by that interface and internally an appropriate message will be created.
not sure i understood what you want to do in the wrapper, but perhaps you can achieve what you want by using the dut_error_struct.
it has set of api, which you can use as hooks (do something when the error is caught) and to query about the specific error.
for example:
extend dut_error_struct {
pre_error() is also {
if source_method_name() == "post_generate" and
source_struct() is a BLUE packet {
out("\nProblem in generation? ", source_location());
// do something for error during generation
};
write() is first {
if get_mesage() ~ "AHB Error..." {
ahb_monitor::increase_errors();
};
};
};
dut_error accepts one parameter, one string. but you can decide of a "separator", that will define two parts to the message.
e.g. - instruct people to write "XXX" in the message, before "first arg" and "second arg".
check that legal else dut_error("ONE thing", "XXX", "another thing");
check that x < 7 else dut_error("failure ", "XXX", "of x not 7 but is ", x);
extend dut_error_struct {
write() is first {
var message_parts := str_split(get_message(), "XXX");
if message_parts.size() == 2 {
out ("First part of message is ", message_parts[0],
"\nand second part of message is ", message_parts[1]
);
};
};
I could get pretty close to what I want using the dut_errorf method combined with a preprocessor directive defining the format string:
#define DUT_FORMAT "first argument is %s and second argument is %s"
check that FALSE else dut_errorf(DUT_FORMAT, "check1", "check2");
but I would still prefer a way that doesn't require this DUT_FORMAT directive and instead uses dut_error_struct or something similar.

How do I print a message if a ValueError occurs?

while answers_right < 3:
ran_number_1 = random.randint(10, 99)
ran_number_2 = random.randint(10, 99)
solution = ran_number_1 + ran_number_2
print(f"What is {ran_number_1} + {ran_number_2}?")
user_answer = int(input("Your answer: "))
if user_answer == solution:
answers_right += 1
print(f"Correct. You've gotten {answers_right} correct in a row.")
elif user_answer != solution:
answers_right = 0
print(f"Incorrect. The expected answer is {solution}.")
if answers_right == 3:
print("Congratulations! You've mastered addition.")
I want to add an additional if statement in case someone types string and return a message that says "Invalid Response" instead of the Traceback Error.
Use of Exception handling in python may be solve your Problem and you can also generate your own error class for particular condition.
if x < 3:
raise Exception("Sorry, no numbers below 3")
Use of throw and raise keyword you can generate your own error.
for more referencelink here
The correct way to solve this problem is to look at the error type in your traceback, and use a try/except block. It will say something like TypeError: error stuff here or ValueError: error stuff also here.
The way you do a try/except is to:
try:
some_code()
that_might()
produce_an_error()
except some_error_type:
do_stuff()
except_some_other_error_type:
do_other_stuff()
So, to catch a ValueError and a TypeError, you might do:
try:
buggy_code()
except ValueError:
print("Woah, you did something you shouldn't have")
except TypeError:
print("Woah, you did something ELSE you shouldn't have")
If you then want the traceback, you can add in a lone "raise" statement below the excepts. For example:
try:
buggy_code()
except ValueError:
print("Woah, you did something you shouldn't have")
raise
except TypeError:
print("Woah, you did something ELSE you shouldn't have")
raise
Errors have evolved to be a lot more useful in modern times. They don't break the entire system anymore, and there are ways of handling them. Try/Except blocks like the above give you the tools to have code that only executes when a specific error or set of errors is raised.

How to indiciate a failure for a function with a void result

I have a function in scala which has no return-value (so unit). This function can sometimes fail (if the user provided parameters are not valid). If I were on java, I would simply throw an exception. But on scala (although the same thing is possible), it is suggested to not use exceptions.
I perfectly know how to use Option or Try, but they all only make sense if you have something valid to return.
For example, think of a (imaginary) addPrintJob(printJob: printJob): Unit command which adds a print job to a printer. The job definition could now be invalid and the user should be notified of this.
I see the following two alternatives:
Use exceptions anyway
Return something from the method (like a "print job identifier") and then return a Option/Either/Try of that type. But this means adding a return value just for the sake of error handling.
What are the best practices here?
You are too deep into FP :-)
You want to know whether the method is successful or not - return a Boolean!
According to this Throwing exceptions in Scala, what is the "official rule" Throwing exceptions in scala is not advised as because it breaks the control flow. In my opinion you should throw an exception in scala only when something significant has gone wrong and normal flow should not be continued.
For all other cases it generally better to return the status/result of the operation that was performed. scala Option and Either serve this purpose. imho A function which does not return any value is a bad practice.
For the given example of the addPrintJob I would return an job identifier (as suggested by #marstran in comments), if this is not possible the status of addPrintJob.
The problem is that usually when you have to model things for a specific method it is not about having success or failure ( true or false ) or ( 0 or 1 - Unit exit codes wise ) or ( 0 or 1 - true or false interpolation wise ) , but about returning status info and a msg , thus the most simplest technique I use ( whenever code review naysayers/dickheads/besserwissers are not around ) is that
val msg = "unknown error has occurred during ..."
val ret = 1 // defined in the beginning of the method, means "unknown error"
.... // action
ret = 0 // when you finally succeeded to implement FULLY what THIS method was supposed to to
msg = "" // you could say something like ok , but usually end-users are not interested in your ok msgs , they want the stuff to work ...
at the end always return a tuple
return ( ret , msg )
or if you have a data as well ( lets say a spark data frame )
return ( ret , msg , Some(df))
Using return is more obvious, although not required ( for the purists ) ...
Now because ret is just a stupid int, you could quickly turn more complex status codes into more complex Enums , objects or whatnot , but the point is that you should not introduce more complexity than it is needed into your code in the beginning , let it grow organically ...
and of course the caller would call like
( ret , msg , mayBeDf ) = myFancyFunc(someparam, etc)
Thus exceptions would mean truly error situations and you will avoid messy try catch jungles ...
I know this answer WILL GET down-voted , because well there are too much guys from universities with however bright resumes writing whatever brilliant algos and stuff ending-up into the spagetti code we all are sick of and not something as simple as possible but not simpler and of course something that WORKS.
BUT, if you need only ok/nok control flow and chaining, here is bit more elaborated ok,nok example, which does really throw exception, which of course you would have to trap on an upper level , which works for spark:
/**
* a not so fancy way of failing asap, on first failing link in the control chain
* #return true if valid, false if not
*/
def isValid(): Boolean = {
val lst = List(
isValidForEmptyDF() _,
isValidForFoo() _,
isValidForBar() _
)
!lst.exists(!_()) // and fail asap ...
}
def isValidForEmptyDF()(): Boolean = {
val specsAreMatched: Boolean = true
try {
if (df.rdd.isEmpty) {
msg = "the file: " + uri + " is empty"
!specsAreMatched
} else {
specsAreMatched
}
} catch {
case jle: java.lang.UnsupportedOperationException => {
msg = msg + jle.getMessage
return false
}
case e: Exception => {
msg = msg + e.getMessage()
return false
}
}
}
Disclaimer: my colleague helped me with the fancy functions syntax ...

Meteor.js : How to run check() when arguments are Mongodb ObjectId's?

In some of my Meteor methods, I'm sending Mongodb ObjectId's from the client as arguments. I'd like to run these through Meteor's check() system but I can't seem to find anything that matches successfully with them.
I've tried
var someObjectId = Meteor.Collection.ObjectId();
check(someObjectId, Meteor.Collection.ObjectId()) // fails
check(someObjectId, { _str : String }) //fails
check(someObjectId, String) //fails
any help much appreciated !
Instead of:
check(someObjectId, Meteor.Collection.ObjectID());
Try without the parentheses:
check(someObjectId, Meteor.Collection.ObjectID);
Edit-
Note that the error message for this check isn't ideal.
check({}, Meteor.Collection.ObjectID);
// Error: Match error: Expected
You could assume the message should be something like
// Error: Match error: Expected ObjectId, got object
You can see why this happens in this snippet from the check package.
https://github.com/meteor/meteor/blob/devel/packages/check/match.js
if (pattern instanceof Function) {
if (value instanceof pattern)
return;
// XXX what if .name isn't defined
throw new Match.Error("Expected " + pattern.name);
}
Meteor.Collection.ObjectID does not have name property.
As an alternative solution, you could simply pass the hexadecimal string as an argument instead of the ObjectID.
var idValidator = Match.Where(function (id) {
check(id, String);
return /[0-9a-fA-F]{24}/.test(id);
});
check(new Meteor.Collection.ObjectID()._str, idValidator);
// success
check('', idValidator);
// Error: Match error: Failed Match.Where validation
check({}, idValidator);
// Error: Match error: Expected string, got object
check([], idValidator);
// Error: Match error: Expected string, got object <--- bug? I expect array
Note, this regular expression is pulled from here.
https://github.com/mongodb/js-bson/blob/master/lib/bson/objectid.js
You should use following to generate a random ObjectID:
var someObjectId = new Meteor.Collection.ObjectID();
As Cuberto said, you can then check it by Meteor.Collection.ObjectID:
check(someObjectId, Meteor.Collection.ObjectID)
Normally when using check() you're not in a position to generate a new Meteor _id. Here's an alternative using Match.check()
First extend the Match object with:
Match._id = Match.Where(function (id) {
check(id, String);
return /[a-zA-Z0-9]{17,17}/.test(id);
});
This is useful because you're likely to be checking _ids in many of your methods.
Now simply:
check(_id,Match._id);
more on this pattern
Complete answer to the original question:
First, define a matcher for a single object in your array of arguments:
Match._id = Match.Where(function (id) {
check(id, String);
return /[a-zA-Z0-9]{17,17}/.test(id);
});
Then you can call:
check(MyArrayOfArguments, [Match._id])

In D, how to pass an empty string? (to gtkD)

Using D1 with phobos
I have a text entry field, instance of gtk.Entry.Entry,
calling setText("") raises a run time error
Gtk-CRITICAL **: gtk_entry_set_text: assertion `text != NULL' failed
Why? It seems to be a problem with D, I tried this:
string empty = "";
assert (empty != null);
my_entry.setText(empty)
The program terminated as the assertion failed.
How can I work around this?
I don't think D really differentiates between "empty string" and "null string". A cheap workaround would be setText(" ").
[edit] Nevermind that. It's a bug in gtkD. in trunk/src/glib/Str.d (thanks wm4 for finding it), change line 147 to return ""; (remove the .dup).
You should write assert(empty !is null) instead of assert(empty != null)
I used "\0" and it seemed to work,
I don't know if any invisible character got into the text field, but this is based on the assumption that an empty string in C is just \0