Checked exceptions in visitors - antlr4

I am learning ANTLR4 and I have no previous experience with parser generators.
When I define my own visitor implementation, I have to override methods of the BaseVisitor (I am looking for instance at the EvalVisitor class at page 40 of the book). In case my method implementation possibly throws an exception, what should I do? I cannot use a checked exception since the original method has an empty throws clause. Am I expected to use unchecked exceptions? (this seems a bad Java design). For instance, assume that in the EvalVisitor class I want method visitId (page 41) to throw a user-defined exception, say UndefinedId, rather than returning 0. How should I write my code?

You have two options:
Handle the exception inside the visitor method itself.
Wrap your checked exception in an unchecked exception. One possibility is ParseCancellationException, but you'll have to determine for yourself whether or not that makes sense in your application.
try {
...
} catch (IOException ex) {
throw new ParseCancellationException(ex);
}

Related

Does PerformImmediateLogin throw a custom exception? If so, what is the type?

When calling we'd like to be able to catch any exceptions in a try catch and hand over to our handler.
IVaultClient vaultClient = new VaultClient(vaultClientSettings);
try {
vaultClient.V1.Auth.PerformImmediateLogin();
} catch ( Exception e) {
}
Yes, in general, all VaultSharp APIs tend to throw this custom exception.
VaultApiException
See here for the fields.
https://github.com/rajanadar/VaultSharp/blob/master/src/VaultSharp/Core/VaultApiException.cs
However, the PerformImmediateLogin can also throw the Exception type when the HTTP login call to Vault does succeed but the response has an empty AuthInfo object (thus not giving back a vault token). This may or may not happen in real life, but this is the only case where Exception is thrown. Otherwise, you can always expect VaultSharp to throw the VaultApiException type.

Exception handling in transformer

We are facing an issue while exception is encountered in transformer.
Below is the scenario:
We have a router and a transformer with the below configuration
<bean id="commonMapper"
class="com.example.commonMapper"></bean>
<int:router input-channel="channelA" ref="commonMapper"
method="methodA" />
<int:transformer input-channel="channel_2"
ref="commonMapper" method="methodB"
output-channel="channelC"></int:transformer>
CommonMapper.java :
public String methodA(SomeBean someBean) {
if (<some business condition example someBean.getXValue()>) {
return "channel_1";
} else if(<some condition>) {
return "channel_2"; // Assuming it enters this condition, based on this the above transformer with input-channel="channel_2" gets called
}else if (<some condition>) {
return "channel_3";
} else {
return "channel_4";
}
}
public SomeBean methodB(Message<SomeBean> message)
throws Exception{
SomeBean someBean = message.getPayload();
someBean.setY(10/0); // Purposely introducing an exception
}
While debugging the application, we found that whenever an exception is encountered in methodB(), the control goes back to router reference method i.e. methodA() and again satisfy the condition and calls the transformer (with input-channel="channel_2"). This repeats for certain iteration. And then exception is logged via AnnotationMethodHandlerExceptionResolver -> resolveException.
Below are the queries:
Why does the router gets called again when it encounters an exception in transformer?
Is it the bug or the normal behavior?
How to tackle this issue?
Please let me know if you need any more details around it.
The Spring Integration flow is just a plain Java methods chain call. So, just looks at this like you call something like: foo() -> bar() -> baz(). So, when exception happens in the last one, without any try...catch in the call stack, the control will come back to the foo() and if there is some retry logic, it is going to call the same flow again.
I'm not sure what is your AnnotationMethodHandlerExceptionResolver, but looks like your talk about this one:
Deprecated.
as of Spring 3.2, in favor of ExceptionHandlerExceptionResolver
#Deprecated
public class AnnotationMethodHandlerExceptionResolver
extends AbstractHandlerExceptionResolver
Implementation of the HandlerExceptionResolver interface that handles exceptions through the ExceptionHandler annotation.
This exception resolver is enabled by default in the DispatcherServlet.
This means that you use pretty old Spring. I don't think that it is related though, but your top of the call stack is Spring MVC. You need to take a look there what's going on with the retry.
And answering to all you question at once: yes, this is a normal behavior - see Java call explanation above. You need to debug Spring code from the IDE to figure out what is going on the MVC level

Get invoke listener name and URL from DAO class [duplicate]

For diagnostic purposes I sometimes need to store the call stack that lead to a given state transition (such as granting a lock, committing a transaction, etc.) so that when something goes wrong later I can find out who originally triggered the state transition.
Currently, the only way I am aware of to retrieve the call stack looks like the following code snippet, which I consider terribly ugly:
StackTraceElement[] cause;
try {
throw new Exception();
} catch (Exception e) {
cause = e.getStackTrace();
}
Does somebody know of a better way to accomplish this?
I think you can get the same thing with:
StackTraceElement[] cause = Thread.currentThread().getStackTrace();
Well, you can improve it slightly by not actually throwing the exception.
Exception ex = new Exception();
ex.fillInStackTrace();
StackTraceElement[] cause = ex.getStackTrace();
Actually, I just checked: the constructor calls fillInStackTrace() already. So you can simplify it to:
StackTraceElement[] cause = new Exception().getStackTrace();
This is actually what Thread.getStackTrace() does if it's called on the current thread, so you might prefer using it instead.
If you want it as a String and use Apache Commons:
org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(new Throwable())
There's a new option since JDK 9: StackWalker
It isn't as expensive as Thread.currentThread().getStackTrace().
see also How Expensive is Thread.getStackTrace()?

c# Throw new Exception with in Loop OK?

I've a list of records retrieved through external web service. Some of the data are rubbish and would like to log the record that failed by throwing a new exception.
Wondering if this is best way to handle, as i read exception can impact the performance?
Pseudo code e.g.
try
Loop through listOfRecords
perform logic.
catch
throw new exception (record details)
It depends on what you want to do with the rest of the records when an exception is encountered. Your current implementation would terminate the loop on the first error.
If, however, you simply want to mark the record in some way as "unprocessed" or "errored" and continue with the remaining records, you'd want to handle the error entirely within the loop:
foreach (var record in records)
{
try
{
Process(record);
}
catch (TypedException ex)
{
LogError(ex);
MarkAsUnprocessed(record, ex);
// respond in some other way as well?
}
}
Ultimately, the exception handling logic belongs wherever it logically makes sense to handle the exceptions. Catching exceptions is the easy part, that's a simple construct of the language being used. Meaningfully handling exceptions is another story entirely, and is a logical construct independent of the language being used.
Edit: It's also very much worth noting that your pseudo-code implies this way of handling exceptions:
try
{
// something
}
catch
{
throw new Exception("something");
}
This is very bad practice. Throwing an entirely new exception essentially tosses out the exception that was caught, which gets rid of some very useful debugging information (not the least of which being the stack trace). If you want to immediately log the exception and then let it continue up the stack, simply use the keyword throw by itself:
try
{
// something
}
catch (Exception ex)
{
// log the exception
throw;
}
If you want to add context to the exception, you can modify its properties before throwing it again. Or perhaps even better, throw a custom exception (not Exception) and attach the existing one as the InnerException property:
try
{
// something
}
catch (Exception ex)
{
throw new RecordProcessingException("some additional context", ex);
}
If, on the other hand, there's nothing meaningful to be done with the exception in the current context, don't even catch it at all. Let it bubble up the stack until it encounters code that can meaningfully handle it.
It's not the best way, since you only need the log-writing functionality. Just write to the log and continue the loop.

How to let program to run instead of an exception in c#?

I am writing a program to read all files from an array.
Suppose in between if any file is corrupt or any reason it will stop the execution in between and throw an exception
I want to let the code running till end and at last it logged the error files instead of throwing exception?
try{
doSomethingThatMayRaiseAndException();
}
catch (Exception e){
NotifyTheUserThatSomethingBadJustHappened();
}
Exception here is the base class for exceptions, you may need to use a more specific one if you want to provide the user with details. But right now, what you need to learn is how to deal with exceptions. You can use the link provided by Oded, it is a good start. Then note what is the raised exception you need to handle, and handle it.

Resources