I am trying to handle the exception produced by Javaparser library due to token error. I used the following code.
String content=getTheSource();
ByteArrayInputStream bin=new ByteArrayInputStream(content.getBytes());
try
{
CompilationUnit cu=JavaParser.parse(bin);
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
//my handling code here
}finally{
bin.close();
}
However, the exception was never caught and I am getting a different exception generated from somewhere else. I got this exception:
Exception in thread "main" japa.parser.TokenMgrError: Lexical error at line 1, column 16. Encountered: "#" (35), after : ""
at japa.parser.ASTParserTokenManager.getNextToken(ASTParserTokenManager.java:2247)
at japa.parser.ASTParser.jj_ntk(ASTParser.java:9986)
at japa.parser.ASTParser.ClassOrInterfaceBody(ASTParser.java:926)
at japa.parser.ASTParser.ClassOrInterfaceDeclaration(ASTParser.java:604)
at japa.parser.ASTParser.TypeDeclaration(ASTParser.java:524)
at japa.parser.ASTParser.CompilationUnit(ASTParser.java:269)
at japa.parser.JavaParser.parse(JavaParser.java:81)
at japa.parser.JavaParser.parse(JavaParser.java:94)
at misc.CompileTest.main(CompileTest.java:45)
Any idea, how to handle the exception? Thanks in advance
As the name indicates, TokenMgrError is an error. So you have to catch an Error instead of Exception. If you want to catch both Error and Exception, you can use Throwable instead.
Originally, this error is throwed by JavaCC (TokenMgrError) which is used by Javaparser.
From version 3 on, JavaParser will/should not throw this error anymore.
Related
Im creating a dead letter channel errorhandler like below
errorHandler(deadLetterChannel("direct:myDLC").useOriginalMessage().maximumRedeliveries(1));
from("direct:myDLC")
.bean(MyErrorProcessor.class);
The Bean MyErrorProcessor should be able to handle all types of checked and unchecked exceptions like below..
public void process(Exchange exchange) throws Exception {
Exception e=(Exception)exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
e.printStackTrace();
if(e instanceof MyUncheckedException){
logger.error("MyUncheckedException: "+((MyException) e).getErrorCode()+" : "+((MyException) e).getErrorDesc());
}else if(e instanceof MyException){
logger.error("MyException: "+((MyException) e).getErrorCode()+" : "+((MyException) e).getErrorDesc());
}
}
But after exception is handled the original message should be redirected to route's endpoint.. how to continue route once exception handled like this??
Using continued() will work, it will ignore the error and continue to process, so then you would probably want to handle the specific Exception
see http://camel.apache.org/exception-clause.html
onException(MyException.class)
.continued(true)
;
If you would use .useOriginalMessage() on this exception handling, the original message would be the message that is continued.
So I'm working in VB.Net and I am occasionally getting an unhandled exception. What I don't get is that I have a catch block for said exception.
Here's a sample of what I'm talking about.
Try
If MyTask3 IsNot Nothing Then
MyTask3.Control(TaskAction.Abort)
MyTask3.Dispose()
End If
Catch ex As DaqException
ErrorMessage = ex.ToString()
MyTask3.Dispose()
Catch ex As AccessViolationException
ErrorMessage = ex.ToString()
MyTask3.Dispose()
Catch ex As ObjectDisposedException
ErrorMessage = ex.ToString()
Catch ex As Exception
ErrorMessage = ex.ToString()
Finally
Task3Aborted = True
End Try
So in testing the above code snippet, I sometimes get an AccessViolationException (which the debugger says is unhandled even though there is a Catch for it). I step through the code and the catch that execute is the ObjectDisposedException.
So is this a case where I'm getting two exceptions thrown and only one is handled while the other is unhandled? Is that even possible?
Thanks in advance for any help.
Starting with the .NET Framework 4, AccessViolationException exceptions thrown by the common language runtime are not handled by the catch statement in a structured exception handler if the exception occurs outside of the memory reserved by the common language runtime. To handle such an AccessViolationException exception, you should apply the HandleProcessCorruptedStateExceptionsAttribute attribute to the method in which the exception is thrown.
I think this is your problem. You can read more here.
Mark the function with the HandleProcessCorruptedStateExceptions attribute to handle this exception. You may need to add legacyCorruptedStateExceptionsPolicy=true to your app.config.
You can read this if you want to understand whats happening.
I have a problem with the following code example:
Windows::Storage::StorageFolder^ location = Package::Current->InstalledLocation;
try
{
task<StorageFile^> GetFileTask(location->GetFileAsync(sn));
GetFileTask.then([=](StorageFile^ file)
{
try
{
task<IBuffer^> ReadFileTask(FileIO::ReadBufferAsync(file));
ReadFileTask.then([=](IBuffer^ readBuffer)
{
// process file contents here
});
}
catch(Platform::Exception^ ex)
{
// Handle error here
}
});
}
catch(Platform::Exception^ ex)
{
// Handle error here
}
When using a filename that doesn't exist the function throws an exception:
Unhandled exception at 0x0FFCC531 (msvcr110d.dll) in GameTest2.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.
I've been searching the internet and this exception breaks only when connected to the debugger. I'm using VS 2012. I've turned off all the relevant 'break on exception' but it still causes the debugger to break and non of my handlers are getting a chance to handle the exception.
If the file is missing I would expect the GetFileAsync method to throw a 'File doesn't exist' exception. Not sure why it keeps throwing the 'Invalid parameter' exception.
This is starting to bother me and I just can't find any known solution to this issue. Anyone have any ideas?
I'm going to try and change the method to not use the task<> code. Instead I'll call the GetFileAsync using 'await'. However I believe 'await' will just cause the calling thread to wait until the GetFileAsync has finished, which kind of defeats the point of asynchronous loading.
I'm wondering if this is a common issue with exception handling when using tasks.
Update:
OK, I've now found the solution:
task<StorageFile^>( location->GetFileAsync(sn)).then([](StorageFile^ openedFile)
{
return FileIO::ReadBufferAsync(openedFile);
}).then([](IBuffer^ readBuffer)
{
// Process file
}).then([](task<void> t)
{
try
{
t.get();
}
catch(Platform::Exception^ e)
{
// Handle error
}
});
It seems there needs to be an extra 'then' condition added to the end of the chain to pick up the exception.
Take the following try-catch statement in a WCF-Service
Try
'Here some method is being called.
Return myBs.PerformDailyUpdate()
Catch ex As Exception 'Exception is not being caught here
If service IsNot Nothing AndAlso service.HasWarnings Then
TextFileTracer.Write(String.Format("Warning in method: '{0}'.", name))
TextFileTracer.Write(service.GetWarnings)
End If
Try
TextFileTracer.Write("Error in dbmanager: " & service.HasErrors.ToString)
Catch ex2 As Exception
End Try
TextFileTracer.Write(String.Format("Error in method: '{0}'.", name))
TextFileTracer.Write(ex.Message & vbCrLf & ex.StackTrace)
End Try
End Function 'Exception shows here while debugging
In that method (PerformDailyUpdate) an ASMX-Webservice (.Net 2.0) is being called. This webservice throws occassionaly an SOAPException caused from a method being called from that webservice.yet somehow this SOAPException is nog being caught by the method above.
My Question: Why isn't the SOAPException being Caught? Are there some characteristics that seperates a SOAP-Exception from normal 'exceptions' generated (that in turn cause it not be caught)?
Note: The code written here is not mine. So Please don't judge me on it
ExceptionMessage (First part)
System.Web.Services.Protocols.SoapException: Unexpected application error: SqlException.
ADF.ExceptionHandling.GlobalExceptions.UnexpectedException: Unexpected application error: SqlException.
System.Data.SqlClient.SqlException: Incorrect syntax near ')'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
....
Thanks
Scheme (how this clarifies the situation somewhat):
Internal DailyTriggerMechanism -----> WCF - Service -----> ASMX-Webservice ----> DB2/SQL
(Origin code above) (Exception being thrown)
Inside the WCF-Service the data recieved is being manipulated to fill specific tables. The AMSX-Webservice may not change in this situation.
I think a normal exception should be able to catch that unhandled error you're listed, but you might try a SOAP-specific, and/or SQL-related exception, in addition to your regular exception.
Like:
try {
//your failing code
}
catch (SOAPException se)
{
//your response }
catch (SQLException sqle)
{
//your response
}
catch (Exception e)
{
//your response
}
I have the following code
Try
'Some code that causes exception
Catch ex as ExceptionType1
'Handle Section - 1
Catch ex as ExceptionType2
'Handle section - 2
Catch ex as ExceptionType3
'Handle section - 3
Finally
' Clean up
End Try
Suppose ExceptionType1 is thrown by the code which is handled by section - 1. After handling that in section-1, can I have control passed to section-2/section-3? Is that possible?
Change the code to catch all the exceptions in one block and determine the type and execution path from there.
You could call functions in the exception handlers.
Try
'Some code that causes exception'
Catch ex as ExceptionType1
handler_1()
handler_2()
handler_3()
Catch ex as ExceptionType2
handler_2()
handler_3()
Catch ex as ExceptionType3
handler_3()
Finally
handler_4()
End Try
You haven't specified a language, and i don't know the language, so i answer generally.
You can't do that. If you want to have common code, put that either into finally, or if it only needs to be executed for some catching cases, you can copy that code into the respective cases. If the code is bigger and you want to avoid redundancy, you can put it into a function of its own. If that would reduce the readability of your code, you can nest your try/catch blocks (at least in Java and C++. I don't know about your language). Here is an example in Java:
class ThrowingException {
public static void main(String... args) {
try {
try {
throw new RuntimeException();
} catch(RuntimeException e) {
System.out.println("Hi 1, handling RuntimeException..");
throw e;
} finally {
System.out.println("finally 1");
}
} catch(Exception e) {
System.out.println("Hi 2, handling Exception..");
} finally {
System.out.println("finally 2");
}
}
}
This will print out:
Hi 1, handling RuntimeException..
finally 1
Hi 2, handling Exception..
finally 2
put your common code into the outer catch block. Doing it using the nested version also handles cases where an exception occurs without you explicitly re-throwing the old in a catch block. It may fit to what you want even better, but it may also not.
I think you could get the behavior you want if you do nested try blocks. Once an exception is thrown, execution goes to the catch block. If nothing is rethrown, it moves on to finally.