How to catch the exception in the lexer? In parser if a rule is failed (or mismatched with the given input stream ) Antlr will throw the exception and we can easily catch this exception.Catch the exception in the lexer in Antlr3.Ref:Error handeling in antlr 3.0...
attribute :
Value1 integer1["Value1"] { System.out.println("Accepted"); }
| Value2 integer2["Value2"] { System.out.println("Accepted"); }
;
catch[Exception e] {System.out.println("General error Reported");}
It will work in parser.But how can I catch the exception in the lexer itself?.Say in parser I am having the rule like
str:STRING|DIGIT;
and in lexer STRING is defined as
STRING : ('"' 'a'..'z' '"');
My input stream is "God"....If I miss the double quote or if I put the extra double quote then I want that exception should be caught in the lexer itself...Is there any method to do this? Is it possible?
Override one or more of the following methods to use ANTLR's own exception handling (this applies to both lexer and parser) - note that this applies only to exceptions caused by input mismatch:
emitErrorMessage() - to handle how the message is displayed to user
getErrorHeader() - to change how error message header is created
getErrorMessage() - to change how the description of error is created
displayRecognitionError() - to change how the message is created from the exception, or to completely change how the exception is handled
The key difference between ANTLR's lexer and parser is that in lexer, there is no start rule or "current" rule - the lexer tries to match all available rules in parallel. So if a mismatch occurs, it cannot be attributed to any particular rule (so it also cannot be handled in any particular rule using a catch block).
Related
In a native-C++-Dll (MFC): how to throw an Exception (with some additional text) that can be catched and handled from a .NET-Client?
This is the native-MFC-Dll which wants to throw an Exception:
void RGaugeTVDDataReader::LoadDataFromFile_HandleException(const CString& szPath) const
{
CString sMessage;
sMessage.Format(_T("TVD-File %s"), static_cast<LPCTSTR>(szPath));
/*1*/ AfxThrowFileException(CFileException::genericException, -1, static_cast<LPCTSTR>(sMessage));
/*2*/ throw std::runtime_error(CT2A(sMessage));
}
The Caller is a .Net-Dll which uses the native dll via a .net-generated-COM-Wrapper.
Both variants (/1/ and /2/) fall into the catch-Block of the .Net-Component but what I get here is just a ´System.Runtime.InteropServices.SEHException´ and the exceptionmessage says "External component has thrown an exception.". Included ErrorCode and HResult is 0x80004005. There is no inner exception, nothing to find about my given text and the stacktrace only contains the managed part.
So the question is: how to throw an excpetion from the native-c++-dll so that a .net-client using it via COM can at least see the message-string?
Alternative question: how to catch and handle the thrown exception in .net correctly?
regards
PHP7 introduced the TypeError "exception" (I know it implements throwable rather than extends exception so it's not strictly speaking an exception, but they behave in essentially the same way as far as I can tell) which gets thrown if you enable strict mode for function parameter type hinting.
declare (strict_types = 1);
function square (int $val) : int
{
return $val * $val;
}
var_dump (square ("123"));
The above code should throw a TypeError, which you can optionally catch and attempt to recover from or terminate execution, depending on what is the most appropriate course of action to take.
However, TypeError seems like it would be a bit too generic, and it would be nice if you were able to extend it to convey a bit more information about the failure that occurred:
class TypeNotIntError extends TypeError {} // Throw this when an int was expected
class TypeNotFloatError extends TypeError {} // Throw this when a float was expected
class TypeNotStringError extends TypeError {} // Throw this when a string was expected
// etc
It should be possible to extend TypeError like this because the PHP documentation doesn't state that it's a final class. However, while you can extend TypeError there doesn't seem to be a mechanism that allows you to throw a child of TypeError without manually throwing one inside a function. As a TypeError would already be thrown by the engine if you pass in an invalid parameter type, the ability to extend TypeError seems pretty limited to me.
Is it possible to tell PHP what sort of TypeError subclass a function/method should throw if passed an invalid parameter type? If so, how?
string name = null;
name.ToLower();
In most languages such code would compile. Which languages would catch this and the like errors at compile time ?
The only one I know uptil now is elm: http://elm-lang.org
Rust prevents a lot of errors at compile-time. Rust doesn't have runtime exceptions (other than panic! which crashes the program), instead it uses return values for error handling.
let name = None; // error: mismatched types
let name: Option<String> = None; // ok
name.to_lowercase(); // error: no method named `to_lowercase` found for type `Option`
// correct:
match name {
None => { /* handle None */ },
Some(value) => { value.to_lowercase(); },
}
// or to ignore None and crash if name == None
name.unwrap().to_lowercase();
One of Rust's core concepts that no other language has (afaik) is lifetimes, which prevent dangling references at compile-time. However this is something that garbage-collected and reference-counted languages don't need.
Go doesn't have exceptions. Like Rust, it uses return values to signal errors. But it's not null-safe:
// strings can't be nil:
var name string = nil // error: cannot use nil as type string in assignment
// string pointers can:
var name *string = nil // ok
string.ToLower(*name) // panic: runtime error: invalid memory address
The following languages do have exception handling but might still be helpful to answer the question.
Swift is also safer than average, but it does include runtime exceptions. However, Swift's exceptions are more explicit than those of C++, Java, C#, etc. (e.g. you have to prefix each call to a throwing function with try, and a function declaration must specify whether that function may throw).
let name = nil // error: type of expression is ambiguous without more context
let name: String? = nil // ok
name.lowercaseString // error: value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
name!.lowercaseString // will crash at runtime with: fatal error: unexpectedly found nil while unwrapping an Optional value
name?.lowercaseString // calls method only if name != nil
Kotlin is a safer JVM-language which also compiles to JavaScript. Kotlin also has exceptions.
val name = null
name.toLowerCase() // compile-error
if (name != null)
name.toLowerCase() // ok
name?.toLowerCase() // call only if non-null
Ada is a language designed for safety-critical purposes. According to http://www.adaic.org/advantages/features-benefits/, its "many built-in checks allow the compiler or linker to detect errors that in a C-based language would only be caught during run-time".
Elm, as the OP noted, is an excellent language without runtime exceptions. Another language that seems to be equally committed to safety is Pony.
https://www.ponylang.io/discover/#exception-safe
Here's a list of languages that by default don't allow variables to be null.
This makes them a lot safer, preventing all NullPointerExceptions at compile-time, and clearer because you know where you're allowed to pass null and where not, simply by looking at the code.
Most of these languages also provide many other compile-time safety features.
class MyRouteBuilder extends SpringRouteBuilder {
public void configure() throws Exception {
//initialize camel context here
onException(ChildException.class)
.process(new ChildExceptionHandler())
.handled(true)
.to(errorURI);
onException(ParentException.class)
.process(new ParentExceptionHandler())
.handled(true)
.to(errorURI);
from(startURI)
.processRef("someBeanID")
//other processing here
}
}
Now my "someBeanID" throws ChildException while processing, but ParentExceptionHandler is being invoked for that. Code snippet in "someBeanID" is as below
try {
//some processing
throws new ParentException();
} catch (ParentException e) {
throw new ChildException(e); //being handled by ParentExceptionHandler (why?? should be ChildExceptionHandler??)
throw new ChildException(); //being handled by ChildExceptionHandler (should be)
}
It seems that whenever we wrap any exception, Camel automatically finds the actual wrapped exception and invokes handler for that, instead of invoking handler for wrapper exception. Why is this? Is there any problem in my code ??
Thanks,
Finally resolved....Refer to this
When trapping multiple exceptions, the order of the onException clauses is significant. Apache Camel initially attempts to match the thrown exception against the first clause. If the first clause fails to match, the next onException clause is tried, and so on until a match is found. Each matching attempt is governed by the following algorithm:
If the thrown exception is a chained exception (that is, where an exception has been caught and rethrown as a different exception), the most nested exception type serves initially as the basis for matching. This exception is tested as follows:
If the exception-to-test has exactly the type specified in the onException clause (tested using instanceof), a match is triggered.
If the exception-to-test is a sub-type of the type specified in the onException clause, a match is triggered.
If the most nested exception fails to yield a match, the next exception in the chain (the wrapping exception) is tested instead. The testing continues up the chain until either a match is triggered or the chain is exhausted.
I'm using ScalaTest for testing some Scala code.
I currently testing for expected exceptions with code like this
import org.scalatest._
import org.scalatest.matchers.ShouldMatchers
class ImageComparisonTest extends FeatureSpec with ShouldMatchers{
feature("A test can throw an exception") {
scenario("when an exception is throw this is expected"){
evaluating { throw new Exception("message") } should produce [Exception]
}
}
}
But I would like to add additional check on the exception, e.g. I would like to check that the exceptions message contains a certain String.
Is there a 'clean' way to do this? Or do I have to use a try catch block?
I found a solution
val exception = intercept[SomeException]{ ... code that throws SomeException ... }
// you can add more assertions based on exception here
You can do the same sort of thing with the evaluating ... should produce syntax, because like intercept, it returns the caught exception:
val exception =
evaluating { throw new Exception("message") } should produce [Exception]
Then inspect the exception.
If you need to further inspect an expected exception, you can capture it using this syntax:
val thrown = the [SomeException] thrownBy { /* Code that throws SomeException */ }
This expression returns the caught exception so that you can inspect it further:
thrown.getMessage should equal ("Some message")
you can also capture and inspect an expected exception in one statement, like this:
the [SomeException] thrownBy {
// Code that throws SomeException
} should have message "Some message"