Getting an unhandled exception with a defined catch block - vb.net

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 legacyCorruptedState­­ExceptionsPolicy=true to your app.config.
You can read this if you want to understand whats happening.

Related

SoapException Not Caught in try catch

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
}

Handling exception in Javaparser

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.

default exception handling

What im trying to do within my project is every time i raise a
try
...
catch ex as exception
...some logging code
end try
Have it so that there is a class predefined somewhere to execute some code when a catch is triggered. not sure if it's possible but it would make my life easier and alot less duplication in my code.
something like
public sub NullReferenceException()
runLogginfunction()
end sub
Thanks
You can't both catch an exception and have it automatically logged. You can have one or the other. For desktop apps, you can use the UnhandledExceptionEventHandler to catch and log exceptions, in ASP.NET you can use the global.aspx to the same thing. Or you can catch the exception, and decide what to do with it -- which can include logging, but will have to be handled manually.
why this would not work?
try
...
catch ex as exception
NullReferenceException(ex)
end try
module allstuff
public sub NullReferenceException(ex as exception)
runLogginfunction(ex)
end sub
end module

Catch Exception only in release

HI, I have one global generic exception handler(catch ex as Exception) for all unhandled exceptions from application.
But in debug mode(app runs from VS) I don`t want that exceptions go to this global handler.
Better for me is when VS stops app on place when exception occurs.
How can I do this, or is there some better approach for this?
thanks
finally I found solution:
Try
......
#If DEBUG Then
Catch ex As Exception When False
#Else
Catch ex As Exception
#End If
......
End Try
ps: thanks to JYelton for hint.
edit:simplified solution
You could use a preprocessor directive (this example is C#):
#if DEBUG
// omit exception handling (or use a different one)
#else
// exception handling event subscriber here
#endif

Try Catch block

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.