How to raise an exception in VB.NET - vb.net

How should an exception be raised in VB.NET?

You would throw a new exception.
Have a look at Throw Statement (Visual Basic)
The Throw statement throws an exception that you can handle with
structured exception-handling code (Try...Catch...Finally) or
unstructured exception-handling code (On Error GoTo). You can use the
Throw statement to trap errors within your code because Visual Basic
moves up the call stack until it finds the appropriate
exception-handling code.
EDIT
By request and from the link
Throw New System.Exception("An exception has occurred.")

Related

Exception Not Being Handled in Try Catch [duplicate]

This question already has answers here:
How to overcome StackOverflowException bypassing unhandled exception handling in .NET
(4 answers)
Closed 8 years ago.
I traverse an array of bytes in a Try...Catch block. Something like this:
Try
For Each curByte In bytes
'Do something with bytes.
Next
Return encodedBytes
Catch e As Exception
'handle exception
End Try
Randomly, my program will crash with an unhandled exception on the Next statement in the code block above. The exception is a StackOverflow in mscorlib.dll "unable to evaluate expression".
Why is my exception handling not handling the exception? I'm not sure I know where to begin trying to address this error.
A StackOverflowException cannot be caught, because it's a fundamentally breaking error that .NET generally can't recover from. That's why you're not catching the exception.
However, its cause is generally quite simple to determine: if you check your debugger at the point where the exception occurs and look at the callstack, you will typically see a recursive call (that is, the same method calling itself in a nested fashion). That's what's causing your exception, and you need to fix whatever logic is calling the recursive calls to address the issue.

VB.NET Try/Catch/When - Stay away or does it have its use?

VB.NET has, unlike c#, a feature to conditionally catch exceptions in a Try/Catch/Finally block.
I thought I read somewhere that this is usually bad practice as it encourages people to put (business) logic in the exception handling mecanism and that you essentially end up with a glorified GoTo.
Try
// Do something
Catch ex As MyException When [condition]
//
End Try
So are there legit cases to use the When feature or should we stay away from it?
This has probably already been answered but I was unable to find anything relevant due "When" being a pretty bad keyword for a search.
The usual case I can think of is when you only want to capture a specific exception, based on the content of that exception. E.g.:
Try
// Do something
Catch ex As SqlException When ex.Number = 547
// Constraint Violation
End Try
Which saves you from capturing all SqlExceptions, then examining the Number property, and then having to re-throw the exception if it doesn't match.
See also The good and bad of exception filters:
For instance, if you have a fairly general exception, like COMException, you typically only want to catch that when it represents a certain HRESULT. For instance, you want to let it go unhanded when it represents E_FAIL, but you want to catch it when it represents E_ACCESSDEINED because you have an alternative for that case. Here, this is a perfectly reasonable conditional catch clause:
Catch ex As System.Runtime.InteropServices.COMException When ex.ErrorCode() = &H80070005
The alternative is to place the condition within the catch block, and rethrow the exception if it doesn’t meet your criteria. For instance:
Catch ex As System.Runtime.InteropServices.COMException
If (ex.ErrorCode != &H80070005) Then Throw
Logically, this “catch/rethrow” pattern does the same thing as the filter did, but there is a subtle and important difference. If the exception goes unhandled, then the program state is quite different between the two. In the catch/rethrow case, the unhandled exception will appear to come from the Throw statement within the catch block. There will be no call stack beyond that, and any finally blocks up to the catch clause will have been executed. Both make debugging more difficult. In the filter case, the exception goes unhandled from the point of the original throw, and no program state has been changed by finally clauses.

Ignoring Exceptions in Object Oriented Programming

In some applications, I came across some lines of code which deliberately eats the exceptions. In my application the benefit of doing this is - To ignore the exception and just continue with the loop(The exception handled is for an error thrown inside the loop). The following lines of code looks evil to even an experienced developers. But is sensible to the context(I mean, that is the requirement - to process all the files in the directory).
try{
//some lines of code which might throw exception
}catch(Exception e){
//no code to handle the error thrown
}
What other benefits can ignoring exceptions provide?
If it is a requirement to process all the files, if you get an exception during processing one of them, is not the requirement broken already? Either something failed or the exception is not needed.
If you want to continue the processing handle the exception, then continue. Why not just report the problem with processing a given file,so someone can later process it manually? Probably even stupid cerr << "Hey I had trouble with this file '" << file <<', so I skipped it.\n" would be better than nothing.
Exception is there to signal something. If you are ignoring it either you are doing something nasty, or the exception is not needed.
The only valid reason for ignoring the exception I can think of is when someone throws exceptions at you for no good reason. Then maybe, yeah, ignore.
This is generally the mark of bad code - you always want to handle your exceptions by at a minimum reporting what the exception is. Ignoring exceptions will let your program keep running, but generally exceptions are thrown for a reason and you or the user need to know what that reason is. Doing a catch-all and escaping just means the coder was too lazy to fix whatever problems cropped up.
The exception is if the coder is throwing exceptions merely to pass arguments, which is something I saw on DailyWTF once.
Usually we should not absorb the exception but there can be reason like there is a function which is out of business logic that is just to help some kind of extra functionality, then you do not want your application to break if that function throw the exception in that case you absorb/eat the exception. But I do not recommend the empty catch block, one should log this in ELMAH or other error logging tools for future.
I don't think there any any benefits of ignoring exceptions. It will only cause problems. If you want the code to be executed in the loop, after handling it, it will continue with the loop because exception is handled. You can always process the files in your directory even if you are not doing anything after handling exceptions.
It will be better if you write some log regarding the files for which exception is thrown
If you eat the exception. You may never know what is the actual cause of the problem.
Considerr this example
public class Test {
private int x;
public void someMethod(){
try {
x = 10/0;
} catch (Exception e) {
}
}
public static void main(String[] args) {
Test test = new Test();
test.someMethod();
System.out.println(test.x);
}
}
This will print simply 0 the default value of x as exception occured during division and value was not assigned to x
Here you are supposed to get actual result of the division. Well it will definitely throw an ArithMeticException because we are dividing by zero and we have not written anything in catch block. So if the exception occurs, nothing will be printed and value of x will be 0 always and we can't know whether the division is happend or not. So always handle exceptions properly.

Catch cannot catch type 'Microsoft.Office.Interop.Outlook.Exception'

I have a program in VB.Net that receives mails from Outlook, extracts attachments and inserts the attachments into a table through a query. I would like to put the query/queries in a Try/Catch block, but cannot do so as Outlook exceptions cannot be caught, and it gives me an error, and unless I put a very specific exception, I cannot catch it. Is there a workaround?
Edit:
Try
Catch ex As Exception
End Try
Exception is underlined and when I hover on it, it says: "Catch cannot catch type 'Microsoft.Office.Interop.Outlook.Exception' because it is not in 'System.Exception' or a class that inherits from 'System.Exception'". This is affecting all my other code which I'd like to put into a Try/Catch block. What to do?
OK, I see the problem now.
When you write Exception, VB reads Microsoft.Office.Interop.Outlook.Exception (probably because you have an Import Microsoft.Office.Interop.Outlook statement at the top of your code file).
You need to tell VB explicitly that you mean System.Exception:
Try
...
Catch ex As System.Exception
...
End Try
(Since M.O.I.O.Exception is not a .net exception but simply an Outlook COM class that happens to be called Exception, there'd be no point in trying to Catch it.)
There is not such thing as "XXX exceptions cannot be caught". It probably has a type that you don't known. You should read documentation for the library that you use and find the type of the exception.
Edit: To answer the subject: if you want to catch all exception except one, you should catch all exception and throw again that exception.

Exception handling differences questions

It is possible to catch an exception and throw a new exception which wraps the first exception as an inner exception:
http://msdn.microsoft.com/en-us/library/system.exception.innerexception(VS.71).aspx
Also, if I call a function and it throws a certain error, but I catch it, will the calling code's catch handler execute? If so, and it is of a higher exception type, is this not wrapping the exception?
eg I can throw exception ex of type IndexOutOfRange, log it but rethrow, catch a higher up exception and do something, or I can throw a new exception and wrap an inner exception like:
throw new MyException("some error", ex.InnerException)
Thanks
Yes you can throw an Exception that wraps the first Function
Also, if I call a function and it throws a certain error, but I catch it, will the calling code's catch handler execute?
No.
If so, and it is of a higher exception type, is this not wrapping the exception?
I didnt quite get this one but it looks like the term Wrapper in its original sense.