I'd like to hear, how you check for "Root element is missing", when using XDocument.Parse(); Currently, I'm using a try-catch, to catch the error, but I'd like to hear, if any of you have a more clever way to do it - personally, I'd like to avoid errors, instead of caching them.
I should clarify, the string, which I'm parsing, is returned from WebClient.DownloadString(...);, and therefor, I'm NOT creating the XML myself.
Best regards.
try/catch exception handling is perfectly normal and usual programming style in the .NET framework. And XML has strict syntax rules which the XML parser checks when parsing markup so you need to be prepared to handle any parsing error, try/catch is the right tool for that.
You haven't said whether you control the creation of the string argument you pass to XDocument.Parse. If you don't control it then you can't avoid errors. If you control then make sure you don't use string concatenation or StringBuilders to construct strings with XML, instead make sure you use XML APIs like XmlWriter, that way you would get well-formed XML markup or you would get any error when constructing your markup, not when parsing it. But any errors thrown by XmlWriter are also best handled with try/catch.
Related
In my experience, every language which supports exceptions has a hierarchy of exception types. This allows a single catch clause to match a group of related exceptions by catching their common parent. For example, part of Python's hierarchy:
FloatingPointError < ArithmeticError < Exception < BaseException
Go, on the other hand, famously does not support exceptions and also has "no type hierarchy". Some people think exceptions should be added to Go - would it be possible to do this without adding a type hierarchy?
Are there other languages which have exceptions but no type hierarchy? Do they group related exceptions in some other way?
SuperTalk has effectively no data types, but has exceptions. Basically you throw an error code and check that. That's also how many early macOS application frameworks worked, even in C++.
So just as an object can be approximated by using a simple data structure with a type selector, exceptions can be made to work.
on doFoo
throw "myError"
end doFoo
on startUp
try
doFoo
catch tError
if tError = "myError" then
-- do something about it
else
throw tError
end if
end try
end startUp
Instead of "myError", you can throw any string or number, so you could use a formatted string, like "copyFileError,/path/to/source/file.txt,/path/to/dest/file.txt" (of course with proper escaping of dangerous characters like "," in this case) and then just compare the first item in this list to tell whether it's the error you want to handle.
If you're just going with error numbers without any additional payload, you can segment the number space to get error "classes" e.g. "fatal errors are negative, recoverable ones positive" or "1-100 are file system errors" or whatever (see HTTP status code for an example of using error code ranges to define error classes).
I'd rather post this as a comment, but the sentiment was too long to get across within the limitations of a comment. I am aware that this is primarily opinion based, and I apologize for that.
Go does not support exceptions because it does not need to. Exceptions are a crutch that developers have been lured into becoming dependent on because they don't want to handle errors properly. In Go, it is idiomatic to handle every error, on the spot, every time. If you do this, your programs run better, and you are aware of exactly when/where errors happen and you can fix them. Using catch in other languages ends up being more difficult to debug as you are not always aware of exactly where the error originally happened. By wrapping your code in try catch blocks, you essentially mask the bugs in your code. try and catch are also terribly inefficient because all of the optimizations in the binary grind to a halt as the program has to figure out what unexpectedly happened. Using errors properly in Go circumvents this because you capture errors and handle them, thereby "expecting" them as an eventuality and handling them properly.
In a COM object generally there are two ways of indicating that a function failed (that I'm aware of):
return S_OK and have an [out] parameter to give failure info
return a failure HRESULT, and use ICreateErrorInfo to set the info.
Currently what I am doing is using the failure-HRESULT method for failures that are "really bad", i.e. my object will be basically inoperable because this function failed. For example, unable to open its configuration file.
Is this correct, or should failure HRESULTs be reserved only for things like dispatch argument type mismatches?
The short version:
In COM you should use HRESULTs (and strive to use ISupportErrorInfo, etc.) for most/all types of error conditions. The HRESULT mechanism should be viewed as a form of exception throwing. If you are familiar with that, consider "Error conditions" as anything for which you would normally throw an exception in a language that supports them. Use custom return values for things for which you would not normally use exceptions.
For example, use a failure HRESULT for invalid parameters, invalid sequence of operations, network failures, database errors, unexpected conditions such as out-of-memory, etc. On the other hand, use custom out parameters for things like 'polling, data is not ready yet', EOF conditions, maybe 'checked data and it doesn't pass validations'. There is plenty of discussions out there discussing what each should be (e.g. Stroustrup's TC++PL). The specifics will heavily depend on your particular object's semantics.
The longer version:
At a fundamental level, the COM HRESULT mechanism is just an error code mechanism which has been standardized by the infrastructure. This is mostly because COM must support a number of features such as inter-process (DCOM) and inter-threaded (Apartments) execution, system managed services (COM+), etc. The infrastructure has a need to know when something has failed, and it has a need to communicate to both sides its own infrastructure-related errors. Everybody needs to agree on how to communicate errors.
Each language and programmer has a choice of how to present or handle those errors. In C++, we typically handle the HRESULTs as error codes (although you can translate them into exceptions if you prefer error handling that way). In .NET languages, failure HRESULTs are translated into exceptions because that's the preferred error mechanism in .NET.
VB6 supports "either". Now, I know VB6's so-called exception handling has a painful syntax and limited scoping options for handlers, but you don't have to use it if you don't want to. You can always use ON ERROR RESUME NEXT and do it by hand if you think the usage pattern justifies it in a specific situation. It's just that instead of writing something like this:
statusCode = obj.DoSomething(param1)
If IS_FAILURE(statusCode) Then
'handle error
End If
Your write it like this:
ON ERROR RESUME NEXT
...
obj.DoSomething param1
IF Error.Number <> 0 Then
'handle error
End If
VB6 is simply hiding the error code return value from the method call (and allowing the object's programmer to substitute it for a "virtual return value" via [retval]).
If you make up your own error reporting mechanism instead of using HRESULTs, you will:
Spend a lot of time reinventing a rich error reporting mechanism that will probably mirror what ISupportsErrorInfo already gives you (or most likely, not provide any rich error information).
Hide the error status from COM's infrastructure (which might or might not matter).
Force your VB6 clients to make one specific choice out of the two options they have: they must do explicit line-by-line check, or more likely just ignore the error condition by mistake, even if they would prefer an error handler.
Force your (say) C# clients to handle your errors in ways that runs contrary to the natural style of the language (to have to check every method call explicitly and... likely throw an exception by hand).
Expression Language is not working in the JSP Pages. We are just using JSP Expression Tag but it can throw Exception when the expression result becomes null.
Ex: <%= h.getHtml() %> . Instead we can use ${h.html}
The JSP code generated in ToolTwist widgets you write is plain standard JSP code. While it is possible to use Java Beans, EL, tag libraries and various other features of JSP, most projects find that sticking with the most basic JSP expressions simplifies future maintainability, because the meaning of the code is clearest.
Most tags are designed to strip down the JSP code and make it more HTML-like, at the expense of using special semantics or moving the logic elsewhere. This separation is useful when the JSP will be maintained by a web designer who is not familiar with the application logic, but in the case of ToolTwist that objective is more or less redundant, because pages are changed using the Designer, not by editing JSP code.
Most widgets are written once, and then infrequently changed, so the important consideration is making the code easy to understand at a glance, without needing to think about or investigate any special semantics or tag library definitions. Using the simplest JSP syntax makes debugging and testing easier, and will be appreciated by any programmer who needs to look at the code in the future.
Note that in this context simplest means "easiest to understand" rather than "fewest lines of code."
Regarding your exception, remember that the code within <%= and %> is standard Java code. If the Java code throws an exception, then the JSP code throws an exception. In this case, getHtml() is a method written by you, so if you wish to use it as a string you should probably ensure it does not return null. Alternatively, check it's value before using it:
<%
String html = h.getHtml();
if (html == null) {
html = "";
}
%><%=html%>
Note that a common bad habit is to call the method twice. Best not to do this:
<%= (h.getHtml() == null) ? "" : h.getHtml() %>
Overall, I'd recommend that you change your getHtml() method to return "" where it currently returns null.
I have encountered a strange problem, which I could solve but don't understand why it did occur.
I have build a DLL with COM enabled. In this DLL I have classes that did use the functions CInt, CDec and IsNumeric. If I test these classes from a .NET application then it works ok. But when I called/run these classes from a Win32 application (with COM) then I did get an "E_UNEXPECTED(0x8000FFFF)" error.
After some debugging I found out that the problem would go away if I:
- replaced IsNumeric with Integer.TryParse or Decimal.TryParse
- replaced CInt with Integer.Parse
- replaced CDec with Decimal.Parse
Can anyone explain this? Again, I could solve it by doing this but I would like to know why.
Just a guess.
I think that this is somehow related to the fact that all legacy functions like CInt, CDec, etc are defined in Microsoft.VisualBasic.dll assembly, which appears not to be playing well with COM.
That's pretty strange. Sounds to me like the arguments passed by the unmanaged code caused an exception in the VB.NET code. Your unmanaged code cannot detect managed exceptions. It should be visible in the debug output in the Output window, you should see a first-chance exception with exception code 0xe0434f4e.
Your changes are not a true replacement for CInt/CDec, they'll only handle string arguments. But stranger yet is that CInt() doesn't have trouble with strings, it shouldn't throw.
You are playing fast and loose with argument types though, treating strings as numbers is always trouble. Make sure you declare the argument type. Putting Option Strict On at the top of your source code is a good way to operate the two-by-four.
in VB.NET it is possible to omit parentheses when you call a parameterless function. However this can be very confusing because developers could think that a statement is accessing a property instead of a method. this could result in a performance drop if you are calling the method again and again instead of storing the result in a temp variable.
is there an option in VS2008 or a compiler option to force parentheses on statements that are calling a method?
and if so, would it be also possible that VS will insert missing parentheses automatically if you "format document" (Menu: Edit - Advanced)?
thanks, toebens
No there is no such option in the VB.Net compiler. Parens are optional and there is no warning or error that exist for using a lack of them.
The other reason is that VB.Net is a language which tries to be flexible and get the syntax out of the way of the user. This type of restriction goes against this general philosophy.
Another issue to consider is that it's not a universally enforceable restriction. VB.Net allows for late binding scenarios whenever option strict is set to off. In these scenarios it is impossible for the VB.Net compiler to determine ahead of time if a particular call is a property, statement or not a valid call at all.