Failed Predicate Exception - exception

Can anyone give me some examples of Failed Predicate exception in ANTLR.
and some examples that will clearly explain :- input mismatch VS failed predicate VS no viable alt exceptions in ANTLR. thanks in advance.

The names of the exceptions pretty much explain when they can appear. Only the failed predicate exception is a bit special.
NoViableAlt:
Thrown when you try to match block with several alternatives and none matches. Example:
r: 'a' | 'b';
Input: 'c'.
InputMismatch:
Thrown when you have input that partially matches. Example:
r: 'a' 'b' 'c' EOF;
Input: 'a' 'b' or 'a' 'c' EOF.
FailedPredicateException:
Thrown in certain situations where a path is guarded by a predicate and this path is the only possible match (or a required match), but the predicate prevents matching it. For example:
... | a ({condition}? b)
However if the block with the predicate is optional (so it's not required) then no predicate exception is thrown, like with:
... | a ({condition}? b)?
For more advanced use of these exceptions for generating better error messages see this error listener.

Related

too greedy condition, or misused exception?

I have two alternative code fragments, with an intention to do (approximately) the same:
Closed-ended condition, with 3 cases of inputs resulting into just 2 cases of outputs:
this.showDropdowns ? parseInt(this.uploadForm.get('location').value, 10) : null;
Open-ended conditioning, with 3 possible cases of inputs resulting into 3 recombined (table non-plain matching) cases of outputs:
try {parseInt(this.uploadForm.get('location').value, 10)} catch (ParseIntError e) {return null;}
The first case is strict, allowing only the two resulting options explicitly prepared by the programmer: Either gives null (i), or the parsed value (ii), or the parsing falls (iii) back to the null.
See the Closed/Open questions described on Wikipedia, to understand me what I mean.
The second code-fragment is not so greedy, does not swallow any possible exception, so the values are the two (three) expected by a programmer: The successfully parsed value (a), or there is still an allowed option for any unexpected result, as an explicitly caught Exception (also merging the null input/output case (b) with the parsing error exception (c), the non-null input, to be parsed, but unprocessable), but still yet allowing a fourth case of whatever completely unimaginable in the moment of the programming (d), still letting it to bubble up as an uncaught exception.
The inputs could be just two, in general: null, or an Object.
The outputs on the other hand could be more complicated:
the hardcoded null, after the IF;
the successfully parsed value;
or Exceptions:
Completely wrong Object-type for the particular parsing.
Parsable Object-type, but wrong values in it, in many ways...
So the questions:
Is the first one too naive and too greedy, swallowing too much, or oppositely the aggregation/swallowing is the recommended way?
Would the second be misusing of the mechanism of exceptions, or just the standard plain usage?
Are these known distinguished cases/options, how to resolve problems? These might be even so general, that there are some rules, philosophical how-to's or Good practices, to judge/recognize, when exactly to use the 1st, or the 2nd? So what are the rules, the recommendations? Thanks.

How To Raise Exception with Message in Ada

I'm struggling a little bit to raise exceptions the way I'm used to coming from a C# background.
I have a utility function that expects input values to be in a very specific range, as defined by an external standard. If a value is supplied outside of that range (and there is one value in the middle of the range that is also invalid), then I want to raise an exception to the caller so that they break.
From what I can tell, the syntax is raise Invalid_Argument;
But- is it possible to supply a message with the exception? e.g. the Invalid_Argument exception is somewhat self-explanatory, but I could see further detail specifying what was wrong with the argument. How do I write a brief error message to be stuck into the exception?
It used (Ada 95) to be you had to write
Ada.Exceptions.Raise_Exception (Invalid_Argument’Identity,
"message");
(see Ada95RM 11.4.2(6)) but since Ada 2005 you’ve been able to say
raise Invalid_Argument with "message";
(A2005RM 11.3).
Note that the string part is a string expression, so you can add something to describe the actual invalid value if that would be useful.
First, you can define a [sub]type
[sub]type Valid_Range_For_X is [Integer] range 23 .. 2001;
This will catch most invalid values automatically. If you're using Ada 12, you can add
[sub]type Valid_Range_For_X is [Integer] range 23 .. 2001 with
Dynamic_Predicate => Valid_Range_For_X /= 42;
which will catch the internal invalid value as well. It's usually better to let the language do such checks for you than to do them manually.
If you're using an earlier version of Ada, then you'll have to manually check for the internal value. I usually prefer fine-grained exceptions to a general exception used for many things, differentiated by the exception message. So I would raise something like
X_Is_42
rather than
Invalid_Argument with "X is 42"
This makes it easier to distinguish the 42 case from the (often many) other kinds of invalid arguments. I realize not everyone agrees with this.

Not Found - Exception in OCaml

I'm trying to check a mapping I've made to see if there are any values that match the word I'm sending. But it should return zero when there are no instances found. Instead, it's throwing Exception: Not_found. and exiting.
Is there any way I can catch this error? I thought Some and None were supposed to do the trick.
let word_count word =
match DictMap.find word word_mapping with
| None -> 0
| Some count -> count;;
I assume that DictMap is some result of applying the Map functor. Use try-with (rather than the option type) since find raises an exception rather than returning None when the key is not found.
let word_count word = try DictMap.find word word_mapping with Not_found -> 0;;

Nonboolean receiver--proceed for truth

I have a smalltalk method:
isInvalid
|tmp|
tmp := super isInvalid.
tmp ifTrue: [^ True].
^ instanceVar isNil.
I am getting an exception: Unhandled exception: NonBoolean receiver--proceed for truth thrown on the assignment to temp. I am very sure that super isInvalid returns a Boolean object, so I think I am misunderstanding what this exception means. Does anybody else happen to know?
Long time ago, a worked in Smalltalk fulltime. Good to see that it is alive ...
I see the following error in your code:
You use as a return value the value True, which is (in Smalltalk) the class with only value true.
You have to use instead the value true which is one of the (I think) predefined objects from the VM of Smalltalk which are true, false, nil.
An even better solution would be:
^ super isInvalid or: [instanceVar isNil]
This replaces the whole body or your message, by the boolean expression (which is all the time true or false, no possibility for errors). (Thank's to Fabian for the correct method or:.)
So use the right return value, and the error message will go away.
By the way, the error message Unhandled exception: NonBoolean receiver--proceed for truth is some kind of debugging help, it allows you to proceed, so that you are able to develop faster ... Never saw that again in any other language ...

How do exceptions in Haskell work?

In GHCi:
Prelude> error (error "")
*** Exception:
Prelude> (error . error) ""
*** Exception: *** Exception:
Why isn't the first one a nested exception?
The answer is that this is the (somewhat surprising) semantics of imprecise exceptions
When pure code can be shown to evaluate to a set of exceptional values (i.e. the value of error or undefined, and explicitly not the kind of exceptions generated in IO), then the language permits any value of that set to be returned. Exceptional values in Haskell are more like NaN in floating point code, rather than control-flow based exceptions in imperative languages.
An occasional gotcha for even advanced Haskellers is a case such as:
case x of
1 -> error "One"
_ -> error "Not one"
Since the code evaluates to a set of exceptions, GHC is free to pick one. With optimizations on, you may well find this always evaluates to "Not one".
Why do we do this? Because otherwise we'd overly constrain the evaluation order of the language, e.g. we would have to fix a deterministic result for:
f (error "a") (error "b")
by for example, requiring that it be evaluated left-to-right if error values are present. Very un-Haskelly!
Since we don't want to cripple the optimizations that can be done on our code just to support error, the solution is to specify that the result is a non-deterministic choice from the set of exceptional values: imprecise exceptions! In a way, all exceptions are returned, and one is chosen.
Normally, you don't care - an exception is an exception - unless you care about the string inside the exception, in which case using error to debug is highly confusing.
References: A semantics for imprecise exceptions, Simon Peyton Jones, Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson. Proc Programming Languages Design and Implementation (PLDI'99), Atlanta. (PDF)